From c47a469aec945f719fbbab6877ba9eecd63bce3c Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Tue, 15 Sep 2026 13:35:04 +0800 Subject: [PATCH 01/13] feat(client): accept and leave with Enter, Tab, and Escape in the composer The popup select panel and the model seat hold focus while open, and their Tab fell through to the browser's traversal, leaving an open surface that only a pointer press clears. Both now settle on Enter or Tab, leave on Escape or Shift+Tab, walk with the arrows, and park on the value in use: the panel's highlight on the row its options mark current, the seat's drilled pane on its checked row, with the keyboard handed back to the cell that drilled in when the pane is left. Dismissal rides the conversation's own focus(), so the caret returns where the draft left it instead of at the start. --- ...9-14-composer-selection-keyboard.i18n.yaml | 6 + .../2026-09-14-composer-selection-keyboard.md | 49 ++++++ ...26-09-14-composer-selection-keyboard.zh.md | 49 ++++++ apps/web/tests/declared-reasoning.e2e.ts | 35 ++++- packages/client/ui-commands/README.i18n.yaml | 4 +- packages/client/ui-commands/README.md | 2 +- packages/client/ui-commands/README.zh.md | 2 +- .../src/client/PopupSelectView.tsx | 20 ++- .../client/ui-commands/src/client/popup.ts | 27 +++- .../client/ui-commands/src/client/service.ts | 22 +-- .../tests/popup-view.client.spec.tsx | 46 +++++- .../ui-commands/tests/popup.client.spec.ts | 45 +++++- .../ui-commands/tests/service.client.spec.ts | 42 ++--- .../ui-model-selection/README.i18n.yaml | 4 +- packages/client/ui-model-selection/README.md | 2 +- .../client/ui-model-selection/README.zh.md | 2 +- .../src/client/ModelSelect.module.css | 5 +- .../src/client/ModelSelect.tsx | 82 ++++++++-- .../tests/model-select.client.spec.tsx | 144 ++++++++++++++++++ 19 files changed, 494 insertions(+), 94 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.md create mode 100644 .agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.zh.md diff --git a/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.i18n.yaml b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.i18n.yaml new file mode 100644 index 0000000000..603357d9af --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.md +2026-09-14-composer-selection-keyboard.md: da5c7267bf5506024183e11271dd20357f351104 +2026-09-14-composer-selection-keyboard.zh.md: 0723b390a9cf4abe38322149a06d768d808787d3 diff --git a/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.md b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.md new file mode 100644 index 0000000000..da5c7267bf --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.md @@ -0,0 +1,49 @@ +# Agent Note: Composer selection surfaces mirror the composer's Enter and Escape keys + +Status: implemented + +English | [中文](2026-09-14-composer-selection-keyboard.zh.md) + +## Problem + +Two selection surfaces inside the composer hold focus while they are open, and both left Tab to the browser. + +The popupSelect panel behind `/model` and `/permission` focuses its own search input and dismisses on pointer presses outside the card only. An unconsumed Tab fell through to native focus traversal and left the card open with its search input unfocused — a state no key clears. Its highlight also opened on the topmost row while the option rows mark the session's current value wherever it sits in the provider-grouped list, so the first accept selected a row the user had not chosen instead of confirming the value in use. + +The model seat's dropdown (`ModelSelect`, whose Effort row opens the reasoning-level pane) portals its card and moves real focus with the arrow keys. Focus stays on the trigger while the menu opens, and the walk read "focus is not on a row" as row zero before stepping, so the first forward step landed on the second row. + +## Decision + +`PopupSelectView` settles on Enter or Tab and leaves on Escape or Shift+Tab: Enter and Tab both run `select` on the filtered highlight, Escape and Shift+Tab both dismiss and return focus to the composer through the conversation's own `focus()`, which rides Lexical so the caret comes back where the draft left it rather than at the start. Opening the trigger menu from the composer's launcher button does the same before the menu opens: the menu is a combobox over the editor, so the button cannot hold the keyboard. `↑`/`↓` walk the filtered highlight (wrapping, scrolled into view) and `←`/`→` stay native to the search input. Every one of those keys is consumed, so a row list that is not ready yet swallows Tab as a no-op rather than releasing focus out of the card. + +`PopupSelectController` parks the highlight on the row the loaded list marks as the current value, falling back to the top row when no row is marked or when the search retained across a retry hides it. Typing rebases the highlight to the top of the filtered rows, because a search asks for something other than the current value. Settling on a freshly opened panel therefore confirms the value in use. + +`ModelSelect` keeps `↑`/`↓` as its focus walk over the rows of the shown pane (wrapping; a step taken while the trigger still holds focus enters at the near end). Tab settles: it activates the row the keyboard is on, and with focus still on the trigger it enters the menu at the row of the value in use instead. Escape and Shift+Tab leave a drilled pane first and otherwise close back to the trigger. A pane switch replaces the row that had focus, so each switch names where the keyboard lands: drilling focuses the row of the value in use (its checked row, or the first row when none is marked), and returning to the root pane focuses the cell that opened the pane left. Without that handoff the focus the unmounted row left on the page body sits outside the card's subtree, where its key handling never sees a keystroke. + +`Menu`, the shared anchored dropdown behind the composer's permission seat, the preset chip, file cards, and the settings rows, carries the same pairing: while its list is open, Tab settles the focused row — from the anchor's button, Tab enters the list instead — and Escape or Shift+Tab close it and return focus to the anchor's first button. Only a keyboard already on the anchor or inside the list is intercepted, so Tab presses elsewhere on the page keep the browser's traversal even while a menu is open. Selecting a row hands the keyboard back to the anchor unless the owner moved it itself — a card that focuses its own preview keeps it. The arrows, Home, and End walk the list whether or not `autoFocus` is set — that option now decides only whether opening focuses the first row — the row the keyboard is on carries the same fill a hovered row gets, and closing on Escape or Shift+Tab returns focus to the anchor whenever the menu held it. + +A dismissed menu stays dismissed: `InputTriggerController` records the identity of the hit the user closed — Escape or Shift+Tab, a pointer dismissal, or a settling pick — and a re-track of that same token with the same query leaves the menu closed, so restoring the caret after a dismissal (or a settled command closing the surface it opened) cannot revive it. A new query or another token re-arms it. + +The row contracts are unchanged. Producers already mark their current row `active`, and neither surface gains a drill verb. + +## Alternatives considered + +**Tab walks the rows.** Tab as a second `↓` gives these surfaces no settle gesture on the key the composer already uses for one, and leaves Shift+Tab meaning "walk backwards" instead of the Escape the neighbouring key mirrors. The composer's own pairing — Enter/Tab settle, Escape/Shift+Tab leave — was chosen instead. + +**Let the panel's Tab fall through to native traversal.** The card's dismissal reacts to pointer presses alone, so the residue — open card, unfocused search input — stays until the next click. + +**Keep the panel's highlight on the top row.** It reinstates the fault this decision removes: accepting on a freshly opened panel acts on a row nobody chose. + +**Rebase the panel highlight onto the current value after a search too.** A search expresses interest in rows other than the current value; keeping the highlight on a row the query may have ranked last contradicts the query. + +**Open a drilled pane on its top row.** It parks the keyboard on the topmost level rather than the one in use — the same fault the parked highlight removes — so an accept gesture made without looking switches the effort instead of confirming it. + +**Leave the seat's Tab native.** The seat closes on blur when focus leaves the trigger and the card, so a Tab there was not a dead state. It lost because a surface whose keys mirror the composer's should not single out Tab: Tab settles there like Enter, and Shift+Tab leaves. + +## Verification + +[Seat browser evidence](../../../../apps/web/tests/declared-reasoning.e2e.ts) drives a real Chromium against the shipped bundles: it opens the drilled level pane, walks it with `↑`, settles a level with Tab and asserts the saved effort, then reopens the pane and asserts the keyboard lands on that level rather than the top of the list before Shift+Tab walks back to the drilled cell and closes. [Seat keyboard tests](../../../../packages/client/ui-model-selection/tests/model-select.client.spec.tsx) cover the drilled-pane handoff onto the value in use (and onto the first row when no row is marked), the handoff back onto the cell, the `↑`/`↓` walk with both wraps, Tab settling a focused row and entering the menu from the trigger, Shift+Tab leaving a pane then closing, and Tab staying native while the menu is closed. [Popup view tests](../../../../packages/client/ui-commands/tests/popup-view.client.spec.tsx) cover the shell binding the composer input of its own card, Tab settling the parked highlight with consumption and refocus, Shift+Tab dismissing without settling, Tab consumed while rows load without leaving the card, the arrows staying distinct from the native left/right caret, and the wrap on `↑`/`↓`. [Trigger tests](../../../../packages/client/ui-input-trigger/tests/service.client.spec.ts) cover a dismissal sticking to its hit (Escape, a pointer dismissal, and a settling pick), the same hit re-tracking closed, and a changed query re-arming the menu. [Menu tests](../../../../packages/client/ui-primitives/tests/atoms.client.spec.tsx) cover the arrow walk without `autoFocus` (entering at the near end, wrapping, and stepping over a disabled row), Escape returning focus to the anchor, Tab settling the focused row, Shift+Tab closing back to the anchor, Tab entering the list from the anchor, and an unrelated Tab staying native while the list is open. [Popup controller tests](../../../../packages/client/ui-commands/tests/popup.client.spec.ts) cover the parked highlight, its top-row fallback without a marked row, the re-park inside a search retained across a retry, and the rebase to the top row on typing. The popup panel's Tab has unit coverage only: no Web scenario drives `/model` or `/permission` yet. + +## Consequences + +Accepting on a freshly opened panel confirms the value the session already uses instead of switching it, so Tab settles nothing surprising; a Tab on a walked highlight settles that row, exactly as Enter would. Leaving either surface is Escape or Shift+Tab, and both are consumed while a surface is open, so a keyboard user steps out with Escape or Shift+Tab rather than by tabbing away. The composer's trigger menu keeps its own Tab, which settles or drills the highlighted candidate — its drill verb has no other keyboard route — while Escape and Shift+Tab leave that menu without settling, so the exit gesture never consumes the draft. The same pairing reaches every `Menu` consumer at once, so the composer's permission seat, the preset chip, file cards, and the settings dropdowns all settle on Tab and leave on Shift+Tab. The keys are recorded in each owning module's documentation and README, and the trigger menu's keys stay in the `ui-input-trigger` README. diff --git a/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.zh.md b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.zh.md new file mode 100644 index 0000000000..0723b390a9 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.zh.md @@ -0,0 +1,49 @@ +# Agent Note: composer 的选择界面沿用 composer 的 Enter 与 Escape + +Status: implemented + +[English](2026-09-14-composer-selection-keyboard.md) | 中文 + +## 问题 + +composer 内有两个选择界面在打开期间持有焦点,两者都把 Tab 留给了浏览器。 + +`/model` 与 `/permission` 背后的 popupSelect 面板把焦点放在自己的搜索框上,且只响应卡片之外的指针按压。未被消费的 Tab 于是落到原生焦点遍历上,把卡片留在打开状态、搜索框已失焦——这是一个任何按键都清不掉的状态。它的高亮还总是落在首行,而选项行标记的会话当前值可能位于按 provider 分组的列表中的任意位置,于是第一次接受选中的是用户没有选择过的行,而不是确认正在使用的值。 + +模型位的下拉菜单(`ModelSelect`,「推理等级」行打开其面板)把卡片 portal 出去,并用方向键移动真实焦点。菜单打开期间焦点留在触发器上,而走位把「焦点不在任何行上」当作第 0 行再步进,于是第一次向下移动落在第二行上。 + +## 决策 + +`PopupSelectView` 用回车或 Tab 接受,用 Escape 或 Shift+Tab 离开:回车与 Tab 都对筛选后的高亮行执行 `select`,Escape 与 Shift+Tab 都关闭并通过对话自己的 `focus()` 把焦点还给 composer,该路径走 Lexical,因此光标回到草稿原来的位置,而不是开头。从 composer 的 launcher 按钮打开触发菜单时也在开菜单之前做同样的事:该菜单是挂在编辑器上的 combobox,按钮不能握着键盘。`↑`/`↓` 在筛选后的高亮间移动(循环,滚动进视野),`←`/`→` 仍归搜索框的原生光标。上述按键全部被消费,因此尚未就绪的行列表会把 Tab 当作 no-op 吞掉,而不是把焦点放出卡片。 + +`PopupSelectController` 把高亮停在已加载列表标记为当前值的那一行;没有行被标记,或重试时保留的搜索把该行过滤掉时,退回首行。输入搜索会把高亮重定到筛选结果的首行,因为搜索要找的正是当前值之外的东西。因此在刚打开的面板上接受即确认正在使用的值。 + +`ModelSelect` 的 `↑`/`↓` 仍是在所显示面板行间移动焦点(循环;焦点仍在触发器上时从近端进入)。Tab 执行接受:它激活键盘所在的那一行;焦点仍在触发器上时,改为进入菜单并把焦点放在正在使用的那一行。Escape 与 Shift+Tab 都先退出已下钻的面板,否则关闭并回到触发器。面板切换会替换持有焦点的那一行,因此每次切换都指明键盘的落点:下钻落在正在使用的值那一行(其选中行;没有标记行时为首行),返回根面板则落在打开该面板的那个格子上。没有这一步,已卸载的行留在页面 body 上的焦点就位于卡片自身子树之外,挂在那里的按键处理永远收不到键盘事件。 + +`Menu`——权限档位、预设芯片、文件卡与设置行背后的共享锚定下拉——沿用同一组配对:列表打开期间,Tab 选定聚焦行(键盘在锚点按钮上时,Tab 改为进入列表),Escape 或 Shift+Tab 关闭并把焦点还给锚点的第一个按钮。只拦截已经位于锚点或列表内的键盘,因此页面其它位置按下的 Tab 即使在菜单打开时也仍归浏览器。选定一行会把键盘还给锚点——除非拥有者自己移动了焦点(例如文件卡把自己的预览按钮设为焦点)。`↑`/`↓` 与 Home/End 无论是否设置 `autoFocus` 都在列表中走位——该选项如今只决定打开时是否聚焦首行——键盘所在的那一行使用与悬停行相同的填充(否则键盘走位看不出当前行),而 Escape 或 Shift+Tab 关闭时,只要键盘原本在菜单里就把焦点归还锚点。 + +被关闭的菜单保持关闭:`InputTriggerController` 记下用户关闭的那个命中(Escape/Shift+Tab、指针关闭或一次落定选定)的身份,同一 token 以同一查询重新 track 时菜单保持关闭,因此关闭后恢复光标、或已选定命令关闭它打开的界面,都无法把它召回来;新的查询或另一个 token 才会重新武装。 + +行契约不变。产出方本就标记自己的当前行 `active`,两个界面也都没有新增下钻动词。 + +## 备选方案 + +**Tab 负责走位。** 让 Tab 成为第二个 `↓`,会让这两个界面在 composer 已经用来接受的按键上没有接受动作,并把 Shift+Tab 变成「反向走位」,而不是它相邻按键所镜像的 Escape。最终选择的是 composer 自己的配对:回车/Tab 接受,Escape/Shift+Tab 离开。 + +**让面板的 Tab 落到原生遍历。** 卡片的关闭只响应指针按压,残留状态——卡片打开、搜索框失焦——会一直留到下一次点击。 + +**面板高亮继续停在首行。** 这正是本决策要消除的缺陷:刚打开的面板上接受会作用于没有人选择的行。 + +**搜索之后也把面板高亮重定到当前值。** 搜索表达的是对当前值之外内容的兴趣;把高亮留在查询可能排到末尾的行上与查询相悖。 + +**被下钻的面板落在首行。** 它把键盘停在最上面的一档而不是正在使用的那一档——正是「高亮停在当前值」要消除的缺陷——于是没看就按下的接受动作会切换推理等级,而不是确认它。 + +**模型位的 Tab 保持原生。** 焦点离开触发器与卡片时模型位会因失焦关闭,所以那里的 Tab 并不是死状态。它被否决是因为:一个沿用 composer 按键含义的界面不应把 Tab 单独排除——那里的 Tab 与回车一样接受,Shift+Tab 则离开。 + +## 验证 + +[模型位浏览器证据](../../../../apps/web/tests/declared-reasoning.e2e.ts) 用真实 Chromium 驱动已发布的 bundle:打开已下钻的等级面板,用 `↑` 走位,用 Tab 选定一档并断言保存下来的推理等级,随后重新打开该面板、断言键盘落在那一档而不是列表顶部,再用 Shift+Tab 退回被下钻的格子并关闭。[模型位键盘测试](../../../../packages/client/ui-model-selection/tests/model-select.client.spec.tsx) 覆盖下钻交接落在正在使用的值上(没有标记行时落在首行)、交回给该格子、`↑`/`↓` 的双向循环走位、Tab 选定聚焦行以及从触发器进入菜单、Shift+Tab 先退层再关闭,以及菜单关闭时 Tab 保持原生。[弹窗视图测试](../../../../packages/client/ui-commands/tests/popup-view.client.spec.tsx) 覆盖外壳绑定自己卡片内的 composer 输入框、 Tab 接受停放的高亮并完成消费与焦点归还、Shift+Tab 关闭且不接受、行仍在加载时 Tab 被消费且焦点不离开卡片、方向键与原生左右光标互不干扰,以及 `↑`/`↓` 的循环。[触发流水线测试](../../../../packages/client/ui-input-trigger/tests/service.client.spec.ts) 覆盖关闭粘在它自己的命中上(Escape、指针关闭、落定选定三种)、同一命中重新 track 时保持关闭,以及查询改变后菜单重新武装。[Menu 测试](../../../../packages/client/ui-primitives/tests/atoms.client.spec.tsx) 覆盖不带 `autoFocus` 的方向键走位(从近端进入、两端循环、跳过禁用行)、Escape 把焦点还给锚点、Tab 选定聚焦行、Shift+Tab 关闭并把焦点还给锚点、Tab 从锚点进入列表,以及列表打开期间无关位置的 Tab 保持原生。[弹窗控制器测试](../../../../packages/client/ui-commands/tests/popup.client.spec.ts) 覆盖高亮的停放、没有标记行时退回首行、重试时在保留的搜索内重新停放,以及输入时重定到首行。弹窗面板的 Tab 只有单元覆盖:目前还没有 Web 场景驱动 `/model` 或 `/permission`。 + +## 影响 + +在刚打开的弹窗上接受确认的是会话正在使用的值,而不是切换它,因此 Tab 不会带来意外的结果;对已经走过位的高亮按 Tab 会选定那一行,与回车一致。离开这两个界面用 Escape 或 Shift+Tab,且界面打开期间它们都被消费,键盘用户因此是靠 Escape 或 Shift+Tab 退出,而不是 Tab 走开。composer 的触发菜单保留自己的 Tab:它确认或下钻高亮候选——该菜单的下钻动词没有其他键盘入口——而 Escape 与 Shift+Tab 则离开该菜单且不选定,退出动作因此永不消耗草稿。同一组配对一次性覆盖所有 `Menu` 使用方:composer 的权限档位、预设芯片、文件卡与设置里的下拉都以 Tab 选定、以 Shift+Tab 离开。按键记在各归属模块的说明与 README 中,触发菜单的按键则留在 `ui-input-trigger` 的 README。 diff --git a/apps/web/tests/declared-reasoning.e2e.ts b/apps/web/tests/declared-reasoning.e2e.ts index 9acd2688cb..087c6753cb 100644 --- a/apps/web/tests/declared-reasoning.e2e.ts +++ b/apps/web/tests/declared-reasoning.e2e.ts @@ -76,15 +76,46 @@ describe.skipIf(MODE === 'record')('web e2e: declared reasoning efforts reach th const snapshot = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE) - // Picking a level is the same gesture that saves the default selection, so + // Keyboard: the clicked cell unmounts with its pane, so the drilled pane's + // checked row takes the focus it left behind. ↑↓ walk the rows from there + // and Tab settles the focused one exactly as Enter would. + await expect.poll( + () => levels.nth(0).evaluate(element => element === document.activeElement), + { timeout: 10_000 }, + ).toBe(true) + await page.keyboard.press('ArrowDown') + expect(await levels.nth(1).evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('ArrowDown') + expect(await levels.nth(2).evaluate(element => element === document.activeElement)).toBe(true) + + // Settling with Tab is the same gesture that saves the default selection, so // the effort lands in the Agent default Settings section beside provider/model. - await page.getByRole('menuitemradio', { name: 'High' }).click() + await page.keyboard.press('Tab') + await expect.poll(() => levels.count(), { timeout: 10_000 }).toBe(0) await expect.poll( async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 10_000 }, ).toContain('reasoningEffort: high') await expect.poll(() => trigger.getAttribute('aria-label'), { timeout: 10_000 }) .toBe('选择模型,当前 Acme Think,推理等级 High') + + // Reopening the drilled pane parks the keyboard on the level in use, and + // Shift+Tab walks back out like Escape: to the drilled cell, then closed. + await trigger.click() + await page.getByRole('menuitem', { name: /推理等级/ }).click() + const high = page.getByRole('menuitemradio', { name: 'High' }) + await expect.poll( + () => high.evaluate(element => element === document.activeElement), + { timeout: 10_000 }, + ).toBe(true) + await page.keyboard.press('Shift+Tab') + await expect.poll( + () => page.getByRole('menuitem', { name: /推理等级/ }) + .evaluate(element => element === document.activeElement), + { timeout: 10_000 }, + ).toBe(true) + await page.keyboard.press('Shift+Tab') + await expect.poll(() => page.getByRole('menu').count(), { timeout: 10_000 }).toBe(0) expect(tripwire.pageErrors).toEqual([]) }, 60_000) diff --git a/packages/client/ui-commands/README.i18n.yaml b/packages/client/ui-commands/README.i18n.yaml index 114fb3783e..eb6201046e 100644 --- a/packages/client/ui-commands/README.i18n.yaml +++ b/packages/client/ui-commands/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-commands/README.md -README.md: f802179e08009cd4db8a3b786e52e81b26bb21da -README.zh.md: 1dee58ab42d67a62099d57d4e631e440d3349f21 +README.md: f8cba29179f9960042a4a9e67e86496591a76d08 +README.zh.md: 1cea3ae7aea857f2b2d219abf0a7192c2f222792 diff --git a/packages/client/ui-commands/README.md b/packages/client/ui-commands/README.md index f802179e08..f8cba29179 100644 --- a/packages/client/ui-commands/README.md +++ b/packages/client/ui-commands/README.md @@ -25,7 +25,7 @@ Typing a `/` command opens a registered popup, a client action, a host command's ## Use this package -Mount this plugin alongside `ui-input-trigger` and `ui-conversation`; the `/` source then appears in the trigger menu, and business packages register their command surfaces through `ctx.commandUi`. Typing `/model` opens the registered popup; a host command with an argument claim opens its input or executes directly. The composer's `+` button and a typed `/` open the same menu: an Add section (File, Goal, Plan, Feedback) and a Commands section (Compact, Permission, Model, Export) in usage order, each row with a glyph, a localized title and description, and the command name as an alias where the localized title differs from it. +Mount this plugin alongside `ui-input-trigger` and `ui-conversation`; the `/` source then appears in the trigger menu, and business packages register their command surfaces through `ctx.commandUi`. Typing `/model` opens the registered popup; a host command with an argument claim opens its input or executes directly. The popup holds composer focus: typing filters the loaded rows locally, `↑`/`↓` walk them, Enter and `Tab` accept the highlighted row, and Escape and `Shift+Tab` return to the composer. The highlight opens on the row the options mark as the session's current value, so accepting on a freshly opened panel confirms it. The composer's `+` button and a typed `/` open the same menu: an Add section (File, Goal, Plan, Feedback) and a Commands section (Compact, Permission, Model, Export) in usage order, each row with a glyph, a localized title and description, and the command name as an alias where the localized title differs from it. ### Kinds and decorations diff --git a/packages/client/ui-commands/README.zh.md b/packages/client/ui-commands/README.zh.md index 1dee58ab42..1cea3ae7ae 100644 --- a/packages/client/ui-commands/README.zh.md +++ b/packages/client/ui-commands/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -与 `ui-input-trigger` 及 `ui-conversation` 一起挂载本插件;`/` source 随即出现在触发菜单中,业务包经 `ctx.commandUi` 注册自己的命令表面。键入 `/model` 打开已注册的弹窗;带参数声明的宿主命令打开其输入或直接执行。composer 的 `+` 按钮与键入的 `/` 打开同一个菜单:「添加」小节(文件、目标、计划、反馈)与「指令」小节(压缩、权限、模型、下载日志)按使用频次排列,每行带图标、本地化的标题与说明,本地化标题与命令名不同时还显示命令名作为别名。 +与 `ui-input-trigger` 及 `ui-conversation` 一起挂载本插件;`/` source 随即出现在触发菜单中,业务包经 `ctx.commandUi` 注册自己的命令表面。键入 `/model` 打开已注册的弹窗;带参数声明的宿主命令打开其输入或直接执行。弹窗持有 composer 焦点:键入即在已加载的行上本地筛选,`↑`/`↓` 在行间移动,回车与 `Tab` 接受高亮行,Escape 与 `Shift+Tab` 把焦点还给 composer。高亮落在选项标记为会话当前值的行上,因此在刚打开的弹窗上接受即确认当前值。composer 的 `+` 按钮与键入的 `/` 打开同一个菜单:「添加」小节(文件、目标、计划、反馈)与「指令」小节(压缩、权限、模型、下载日志)按使用频次排列,每行带图标、本地化的标题与说明,本地化标题与命令名不同时还显示命令名作为别名。 ### 种类与装饰 diff --git a/packages/client/ui-commands/src/client/PopupSelectView.tsx b/packages/client/ui-commands/src/client/PopupSelectView.tsx index fa1098258d..808b64340d 100644 --- a/packages/client/ui-commands/src/client/PopupSelectView.tsx +++ b/packages/client/ui-commands/src/client/PopupSelectView.tsx @@ -3,11 +3,12 @@ * store into the conversation.input.overlay anchor. Unlike the slash menu * (combobox — textarea keeps focus), this shell HOLDS focus while open: the * inner search input takes focus, plain typing filters the loaded options - * locally, Enter/↑↓ drive the filtered highlight (scrolled into view), Escape - * dismisses back to the composer, and ←→ keep the search input's native - * caret. Any pointer interaction outside the box dismisses (the click's own - * target takes focus). Closed state renders null; the overlay slot stays - * mounted. The card height clamps to the space above the composer. + * locally, Enter and Tab accept the filtered highlight, ↑↓ walk it (wrapping, + * scrolled into view), and Escape and Shift+Tab dismiss back to the composer. + * ←→ keep the search input's native caret. Any pointer interaction outside the + * box dismisses (the click's own target takes focus). Closed state renders + * null; the overlay slot stays mounted. The card height clamps to the space + * above the composer. */ import { useEffect, useRef } from 'react' import { useSyncExternalStore } from 'react' @@ -95,6 +96,15 @@ export function PopupSelectView({ popup, t }: PopupSelectViewProps) { ev.preventDefault() void popup.select(state.active) return + // Tab settles like Enter and Shift+Tab dismisses like Escape, so the + // card's keys mean what they mean in the composer. Both must be consumed: + // the shell HOLDS focus, and native traversal would leave an open card + // whose search input lost focus. + case 'Tab': + ev.preventDefault() + if (ev.shiftKey) popup.dismiss({ focusComposer: true }) + else void popup.select(state.active) + return case 'Escape': ev.preventDefault() popup.dismiss({ focusComposer: true }) diff --git a/packages/client/ui-commands/src/client/popup.ts b/packages/client/ui-commands/src/client/popup.ts index f7e7b186be..7de9e7307c 100644 --- a/packages/client/ui-commands/src/client/popup.ts +++ b/packages/client/ui-commands/src/client/popup.ts @@ -63,7 +63,12 @@ export interface PopupState { readonly options: readonly SelectOption[] /** Local filter text over the loaded options. */ readonly search: string - /** Highlight index into the filtered row list (0 when empty/pending). */ + /** + * Highlight index into the filtered row list: 0 until options land; afterwards + * the row the loaded list marks as the current value + * ({@link SelectOption.active}), else 0. A search rebases it to the top of the + * filtered rows. + */ readonly active: number /** A select() settlement is in flight: further select/search/highlight no-op until it settles. */ readonly submitting: boolean @@ -93,6 +98,20 @@ export function filterOptions(options: readonly SelectOption[], search: string): return options.filter(o => o.label.toLowerCase().includes(query) || (o.detail?.toLowerCase().includes(query) ?? false)) } +/** + * Highlight index for a freshly loaded row list: the row marked as the current + * value when the live search still shows it, else the top row. Opening parks + * the highlight on the value the session already uses, so an accept gesture + * made without looking confirms that value instead of the topmost row. + * @param options - the loaded rows. + * @param search - the shell's live filter text (non-empty after a retry). + * @returns index into the filtered rows. + */ +function currentIndex(options: readonly SelectOption[], search: string): number { + const at = filterOptions(options, search).findIndex(option => option.active === true) + return at === -1 ? 0 : at +} + /** One open shell's bindings (spec + open-time context + segment snapshot + options-fetch abort). */ interface OpenBinding { readonly command: string @@ -145,7 +164,8 @@ export class PopupSelectController { binding.spec.options(binding.context, binding.abort.signal).then( (options) => { if (this.binding !== binding) return - this.state.set({ ...this.state.getSnapshot(), status: 'ready', options, active: 0, error: null }) + const current = this.state.getSnapshot() + this.state.set({ ...current, status: 'ready', options, active: currentIndex(options, current.search), error: null }) }, (error: unknown) => { if (this.binding !== binding) return @@ -166,7 +186,8 @@ export class PopupSelectController { /** * Replace the local search text (pure local filter — the provider is never - * re-queried) and rebase the highlight onto the new filtered list. + * re-queried) and rebase the highlight to the top of the new filtered list: + * typing searches for something other than the current value. * @param search - the shell search input's text. */ setSearch(search: string): void { diff --git a/packages/client/ui-commands/src/client/service.ts b/packages/client/ui-commands/src/client/service.ts index 4eb4a0483a..055f5c3a00 100644 --- a/packages/client/ui-commands/src/client/service.ts +++ b/packages/client/ui-commands/src/client/service.ts @@ -156,7 +156,7 @@ export class CommandUiRuntime extends Service implements CommandUiContract { * Resolve the per-session popup controller (lazy; dies with the session * scope). The controller's consume callback dispatches the scoped * consume-token event back to this session; focusComposer reaches the - * composer through the overlay slot currency. + * session's composer through the conversation input face. * @param actx - session-scope ctx. * @returns the resident controller. */ @@ -173,33 +173,17 @@ export class CommandUiRuntime extends Service implements CommandUiContract { ? { kind: 'span', span: segment.span } : { kind: 'bare-token', token: segment.token }, }) === true, - focusComposer: () => { this.focusHooks.get(id)?.() }, + // The shell took the keyboard; the composer restores it, caret included. + focusComposer: () => { actx.get('conversation')?.input.for(actx).focus() }, }) popups.set(id, controller) actx.effect(() => () => { controller.dispose() popups.delete(id) - this.focusHooks.delete(id) }, 'command: session popup') return controller } - /** Composer focus hooks by session (the overlay wiring binds the textarea focus here). */ - private readonly focusHooks = new Map void>() - - /** - * Bind one session's composer-focus hook (overlay slot wiring; unbind on unmount). - * @param id - session id. - * @param focus - textarea focus callback. - * @returns the unbind disposer. - */ - bindComposerFocus(id: SessionId, focus: () => void): () => void { - this.focusHooks.set(id, focus) - return () => { - if (this.focusHooks.get(id) === focus) this.focusHooks.delete(id) - } - } - /** * Menu candidates: host catalog + contribution availability, built-in rows * localized, then position filtering; sections for an empty query, the diff --git a/packages/client/ui-commands/tests/popup-view.client.spec.tsx b/packages/client/ui-commands/tests/popup-view.client.spec.tsx index 682c971ec8..2dbfda9bb6 100644 --- a/packages/client/ui-commands/tests/popup-view.client.spec.tsx +++ b/packages/client/ui-commands/tests/popup-view.client.spec.tsx @@ -2,8 +2,9 @@ /** * PopupSelectView interaction spec: the search input takes * focus on open and plain typing filters locally, ↑↓ move the filtered - * highlight while ←→ stay native to the input, Enter selects single-flight, - * Escape dismisses back through focusComposer, outside pointerdown dismisses + * highlight while ←→ stay native to the input, Enter and Tab select + * single-flight, Escape and Shift+Tab dismiss back through focusComposer, + * outside pointerdown dismisses * plainly, the submitting/failed states render pending text and a working * retry button, the highlighted row scrolls into view, and the card height * clamps to the space above the composer. @@ -112,24 +113,56 @@ describe('PopupSelectView', () => { it('ArrowUp/Down move the filtered highlight; ArrowLeft/Right are left to the native caret', async () => { const { search } = await mountOpen() + // Open parks the highlight on the current-value row (Light, index 1). + expect(screen.getAllByRole('option')[1]!.getAttribute('aria-selected')).toBe('true') act(() => { fireEvent.keyDown(search, { key: 'ArrowDown' }) }) let options = screen.getAllByRole('option') - expect(options[1]!.getAttribute('aria-selected')).toBe('true') + expect(options[2]!.getAttribute('aria-selected')).toBe('true') act(() => { fireEvent.keyDown(search, { key: 'ArrowUp' }) }) options = screen.getAllByRole('option') - expect(options[0]!.getAttribute('aria-selected')).toBe('true') + expect(options[1]!.getAttribute('aria-selected')).toBe('true') // fireEvent returns false when preventDefault was called: arrow left/right must NOT be intercepted. expect(fireEvent.keyDown(search, { key: 'ArrowLeft' })).toBe(true) expect(fireEvent.keyDown(search, { key: 'ArrowRight' })).toBe(true) }) + it('Tab accepts the highlighted row like Enter; Shift+Tab dismisses like Escape', async () => { + const onSelect = vi.fn() + const leaving = await mountOpen({ onSelect }) + // false = preventDefault ran: the shell holds focus, so Tab may not fall through. + // Shift+Tab leaves without settling: no pick, focus back to the composer. + expect(fireEvent.keyDown(leaving.search, { key: 'Tab', shiftKey: true })).toBe(false) + expect(onSelect).not.toHaveBeenCalled() + expect(leaving.focusComposer).toHaveBeenCalledTimes(1) + expect(leaving.view.container.childElementCount).toBe(0) + cleanup() + + const settling = await mountOpen({ onSelect }) + // Tab settles the parked highlight — the current value — exactly like Enter. + await act(async () => { fireEvent.keyDown(settling.search, { key: 'Tab' }) }) + expect(onSelect).toHaveBeenCalledExactlyOnceWith(OPTIONS[1], 'ctx-A') + expect(settling.consume).toHaveBeenCalledExactlyOnceWith(SEGMENT) + expect(settling.focusComposer).toHaveBeenCalledTimes(1) + expect(settling.view.container.childElementCount).toBe(0) + }) + + it('Tab is consumed while the rows are still loading: no pick, no focus escape', async () => { + const popup = new PopupSelectController({ consume: () => true, focusComposer: () => {} }) + render() + await act(async () => { popup.open('theme', spec({ options: () => new Promise(() => {}) }), 'ctx-A', SEGMENT) }) + const search = screen.getByRole('textbox', { name: '筛选选项' }) + expect(fireEvent.keyDown(search, { key: 'Tab' })).toBe(false) + expect(document.activeElement).toBe(search) + expect(screen.getByText('正在加载选项…')).toBeTruthy() + }) + it('scrolls the highlighted row into view when the highlight moves', async () => { const { search } = await mountOpen() scrollIntoView.mockClear() act(() => { fireEvent.keyDown(search, { key: 'ArrowDown' }) }) const options = screen.getAllByRole('option') expect(scrollIntoView).toHaveBeenCalledWith({ block: 'nearest' }) - expect(scrollIntoView.mock.instances.at(-1)).toBe(options[1]) + expect(scrollIntoView.mock.instances.at(-1)).toBe(options[2]) }) it('caps the card height at the design maximum when the composer sits low enough', async () => { @@ -144,12 +177,11 @@ describe('PopupSelectView', () => { expect(screen.getByLabelText('/theme 选项').style.maxHeight).toBe('188px') }) - it('Enter selects the highlighted row: onSelect, consume, close, focusComposer', async () => { + it('Enter accepts the parked highlight — the current value on open — then consumes, closes, and refocuses', async () => { const seen: Array<{ option: SelectOption; context: string }> = [] const { view, search, consume, focusComposer } = await mountOpen({ onSelect: (option, context) => { seen.push({ option, context }) }, }) - act(() => { fireEvent.keyDown(search, { key: 'ArrowDown' }) }) await act(async () => { fireEvent.keyDown(search, { key: 'Enter' }) }) expect(seen).toEqual([{ option: OPTIONS[1], context: 'ctx-A' }]) expect(consume).toHaveBeenCalledExactlyOnceWith(SEGMENT) diff --git a/packages/client/ui-commands/tests/popup.client.spec.ts b/packages/client/ui-commands/tests/popup.client.spec.ts index ad559c0e45..90aa599764 100644 --- a/packages/client/ui-commands/tests/popup.client.spec.ts +++ b/packages/client/ui-commands/tests/popup.client.spec.ts @@ -65,7 +65,37 @@ describe('open and options load', () => { expect(popup.state.getSnapshot()).toMatchObject({ open: true, command: 'theme', status: 'pending', search: '', submitting: false, error: null }) release(OPTIONS) await Promise.resolve() - expect(popup.state.getSnapshot()).toMatchObject({ status: 'ready', options: OPTIONS, active: 0 }) + // The highlight parks on the row the list marks as the current value + // (Light at index 1), not on the topmost row. + expect(popup.state.getSnapshot()).toMatchObject({ status: 'ready', options: OPTIONS, active: 1 }) + }) + + it('parks the highlight on the top row when no row marks the current value', async () => { + const rows: SelectOption[] = [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }] + const popup = new PopupSelectController(makeDeps()) + popup.open('theme', spec({ options: () => Promise.resolve(rows) }), CTX_A, SEGMENT) + await Promise.resolve() + expect(popup.state.getSnapshot().active).toBe(0) + }) + + it('a retry re-parks the highlight inside the search text it retained', async () => { + let attempts = 0 + const rows: SelectOption[] = [ + { id: 'sun', label: 'Sun' }, + { id: 'moon', label: 'Moon', active: true }, + { id: 'star', label: 'Star' }, + ] + const { popup } = await readyPopup({ + options: () => { + attempts += 1 + return attempts === 1 ? Promise.reject(new Error('directory down')) : Promise.resolve(rows) + }, + }) + await Promise.resolve() + popup.setSearch('n') // Sun, Moon — the current value sits at filtered index 1 + popup.retry() + await Promise.resolve() + expect(popup.state.getSnapshot()).toMatchObject({ status: 'ready', search: 'n', active: 1 }) }) it('loads options exactly once: search filters locally without re-querying the provider', async () => { @@ -147,14 +177,15 @@ describe('open and options load', () => { }) describe('search / move / highlight over the filtered list', () => { - it('setSearch rebases the highlight to 0 and ignores closed shells and identical text', async () => { + it('setSearch rebases the highlight to the top row and ignores closed shells and identical text', async () => { const { popup } = await readyPopup() + expect(popup.state.getSnapshot().active).toBe(1) // parked on the current-value row popup.move(1) - expect(popup.state.getSnapshot().active).toBe(1) - popup.setSearch('s') - expect(popup.state.getSnapshot()).toMatchObject({ search: 's', active: 0 }) + expect(popup.state.getSnapshot().active).toBe(2) + popup.setSearch('a') // Dark, Sepia + expect(popup.state.getSnapshot()).toMatchObject({ search: 'a', active: 0 }) const before = popup.state.getSnapshot() - popup.setSearch('s') + popup.setSearch('a') expect(popup.state.getSnapshot()).toBe(before) const closed = new PopupSelectController(makeDeps()) closed.setSearch('x') @@ -261,7 +292,7 @@ describe('select', () => { popup.setSearch('x') // locked while submitting popup.move(1) popup.highlight(1) - expect(popup.state.getSnapshot()).toMatchObject({ search: '', active: 0 }) + expect(popup.state.getSnapshot()).toMatchObject({ search: '', active: 1 }) release() await first expect(onSelect).toHaveBeenCalledTimes(1) diff --git a/packages/client/ui-commands/tests/service.client.spec.ts b/packages/client/ui-commands/tests/service.client.spec.ts index 7c9624eed7..935c70440b 100644 --- a/packages/client/ui-commands/tests/service.client.spec.ts +++ b/packages/client/ui-commands/tests/service.client.spec.ts @@ -122,12 +122,15 @@ async function bench(opts: BenchOptions = {}) { }) /** Notices the fake conversation face collected (runDetached routing). */ const notices: Array<{ scope: SessionId | undefined; level: 'info' | 'error'; text: string }> = [] + /** Composer focuses the fake conversation face collected (popup dismissal). */ + const focuses: Array = [] const removeConversation = ctx.provide('conversation', { input: { for: (actx: Context) => ({ notify: (level: 'info' | 'error', text: string) => { notices.push({ scope: scopeOf(actx), level, text }) }, + focus: () => { focuses.push(scopeOf(actx)) }, }), }, }) @@ -146,7 +149,7 @@ async function bench(opts: BenchOptions = {}) { await source.candidates(session, { query: '', position: 'leading', drilled: false, signal: new AbortController().signal }) } return { - ctx, fiber, command, source, mint, warm, listCalls, executeCalls, executions, registered, notices, remote, + ctx, fiber, command, source, mint, warm, listCalls, executeCalls, executions, registered, notices, focuses, remote, removeSessions, removeConversation, } } @@ -939,7 +942,7 @@ describe('popupFor', () => { }) it('dismisses matching popups and confirmations while preserving other commands and drafts', async () => { - const { command, source, mint } = await bench() + const { command, source, mint, focuses } = await bench() const pending = Promise.withResolvers() let pendingSignal: AbortSignal | undefined const onSelect = vi.fn() @@ -967,8 +970,6 @@ describe('popupFor', () => { const other = command.popupFor(mint('other').ctx) const consume = vi.fn(() => true as const) scope.ctx.on('slash/input-consume-token', consume) - const focus = vi.fn() - command.bindComposerFocus(sid('s1'), focus) menuPick(source, 'theme', proj('s1')) menuPick(source, 'theme', proj('s2')) menuPick(source, 'other', proj('other')) @@ -990,7 +991,7 @@ describe('popupFor', () => { expect(second.state.getSnapshot()).toMatchObject({ open: false, options: [] }) expect(onSelect).not.toHaveBeenCalled() expect(consume).not.toHaveBeenCalled() - expect(focus).not.toHaveBeenCalled() + expect(focuses).toEqual([]) }) it('resolves lazily per session; a foreign session gets its own controller; unscoped ctx throws', async () => { @@ -1002,8 +1003,8 @@ describe('popupFor', () => { expect(() => command.popupFor(ctx)).toThrow('requires a session scope') }) - it('a successful select dispatches the scoped consume-token and fires the bound composer focus', async () => { - const { command, source, mint } = await bench() + it('a successful select dispatches the scoped consume-token and focuses the composer', async () => { + const { command, source, mint, focuses } = await bench() const onSelect = vi.fn() command.register(themeContribution({ ui: themeUi({ onSelect }) })) const scope = mint('s1') @@ -1012,38 +1013,13 @@ describe('popupFor', () => { consumes.push(r) return true }) - const focus = vi.fn() - command.bindComposerFocus(sid('s1'), focus) - expect(menuPick(source, 'theme', proj('s1'), 6)).toBe('handled') const popup = command.popupFor(scope.ctx) await Promise.resolve() // options land await popup.select(0) expect(onSelect).toHaveBeenCalledExactlyOnceWith({ id: 'dark', label: 'Dark' } satisfies SelectOption, proj('s1')) expect(consumes).toEqual([{ guard: { kind: 'span', span: { start: 0, end: 6, draftRev: 3 } } }]) - expect(focus).toHaveBeenCalledTimes(1) - }) - - it('unbinding an old composer preserves its replacement and unbinding the current one removes focus', async () => { - const { command, source, mint } = await bench() - command.register(themeContribution()) - const scope = mint('s1') - scope.ctx.on('slash/input-consume-token', () => true) - const oldFocus = vi.fn() - const newFocus = vi.fn() - const unbindOld = command.bindComposerFocus(sid('s1'), oldFocus) - const unbindNew = command.bindComposerFocus(sid('s1'), newFocus) - unbindOld() - menuPick(source, 'theme', proj('s1')) - await Promise.resolve() - await command.popupFor(scope.ctx).select(0) - expect(oldFocus).not.toHaveBeenCalled() - expect(newFocus).toHaveBeenCalledOnce() - unbindNew() - menuPick(source, 'theme', proj('s1')) - await Promise.resolve() - await command.popupFor(scope.ctx).select(0) - expect(newFocus).toHaveBeenCalledOnce() + expect(focuses).toEqual([sid('s1')]) }) it('the enter path opens with the bare-token guard', async () => { diff --git a/packages/client/ui-model-selection/README.i18n.yaml b/packages/client/ui-model-selection/README.i18n.yaml index 3b7302fb78..b3485170c3 100644 --- a/packages/client/ui-model-selection/README.i18n.yaml +++ b/packages/client/ui-model-selection/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-model-selection/README.md -README.md: f3c373619fec0482876d8ac540f06e188b5b34d9 -README.zh.md: b8ee9cd73bb3fd5cdf0d0ecd8559b271c5abc933 +README.md: b3c3b25c258dd1fd8088eb7d699806f6ecd2cc1a +README.zh.md: e705c4f1a309da66099abba6cc3cd8a2e9b26b0e diff --git a/packages/client/ui-model-selection/README.md b/packages/client/ui-model-selection/README.md index f3c373619f..b3c3b25c25 100644 --- a/packages/client/ui-model-selection/README.md +++ b/packages/client/ui-model-selection/README.md @@ -25,7 +25,7 @@ The Web GUI lets users switch the model and reasoning effort for an existing ses ## Use this package -Mount this plugin alongside `ui-conversation` and the commands package; the composer then shows the model seat next to the pending indicator, and `/model` opens the same directory as a popup. Both surfaces show the host-reported current selection when the exact provider/model pair remains in the advertised groups; a missing catalog row leaves the routable selection intact while the trigger prompts `Select model`. +Mount this plugin alongside `ui-conversation` and the commands package; the composer then shows the model seat next to the pending indicator, and `/model` opens the same directory as a popup. While the seat's menu is open, `↑`/`↓` move focus across the rows of the shown pane, Tab settles the focused row, and Escape and `Shift+Tab` leave a drilled pane first and otherwise close back to the trigger. Drilling lands on the row of the value in use, and going back lands on the cell that opened the pane left. Both surfaces show the host-reported current selection when the exact provider/model pair remains in the advertised groups; a missing catalog row leaves the routable selection intact while the trigger prompts `Select model`. ### Model and effort diff --git a/packages/client/ui-model-selection/README.zh.md b/packages/client/ui-model-selection/README.zh.md index b8ee9cd73b..e705c4f1a3 100644 --- a/packages/client/ui-model-selection/README.zh.md +++ b/packages/client/ui-model-selection/README.zh.md @@ -25,7 +25,7 @@ Web GUI 允许用户通过 `/model` 弹窗或 composer 模型控件切换既有 ## 使用本包 -与 `ui-conversation` 及命令包一起挂载本插件;composer 随即在待处理指示器旁显示模型位,`/model` 则以弹窗打开同一份目录。当确切提供方/模型对仍在已公布分组中时,两个界面都显示 Host 报告的当前选择;目录行缺席时,可路由的选择保持不变,触发器提示 `Select model`。 +与 `ui-conversation` 及命令包一起挂载本插件;composer 随即在待处理指示器旁显示模型位,`/model` 则以弹窗打开同一份目录。模型位菜单打开期间,`↑`/`↓` 在所显示面板的行间移动焦点,`Tab` 选定聚焦行,Escape 与 `Shift+Tab` 先退出已下钻的面板,否则关闭并回到触发器。下钻落在正在使用的那一行,返回则落在打开该面板的格子上。当确切提供方/模型对仍在已公布分组中时,两个界面都显示 Host 报告的当前选择;目录行缺席时,可路由的选择保持不变,触发器提示 `Select model`。 ### 模型与推理强度 diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.module.css b/packages/client/ui-model-selection/src/client/ModelSelect.module.css index b2cb715287..fdec30ecf3 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.module.css +++ b/packages/client/ui-model-selection/src/client/ModelSelect.module.css @@ -34,7 +34,10 @@ } .trigger:focus-visible { - box-shadow: 0 0 0 2px var(--dsw-alias-border-l3); + /* The same fill a hovered trigger gets: the trigger is one of the row-like + controls of the composer, and the ring its neighbours never drew read as a + different kind of state. */ + background: var(--dsw-alias-interactive-bg-hover); } .trigger:disabled { diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.tsx b/packages/client/ui-model-selection/src/client/ModelSelect.tsx index e9fc0195ef..df4137a2d8 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.tsx +++ b/packages/client/ui-model-selection/src/client/ModelSelect.tsx @@ -5,11 +5,17 @@ * each drilling into its own list — the provider-grouped model list over * the shared directory, and the effort levels. The trigger (313:14108's * ToggleButton) shows both: model name + effort in the caption tone. - * Data and submission ride the SAME per-session ModelDirectory as the - * /model popup; exact-model reasoning metadata and the selected effort come - * from the Host rather than a client-owned vocabulary. A rejected selection - * announces through the shared transient Toast anchored to the composer - * card; the in-menu strip with Retry remains the catalog-load surface. + * While open, ↑/↓ move focus across the rows of the shown pane (wrapping; a + * step taken while the trigger still holds focus enters at the near end), Tab + * settles like Enter, and Escape and Shift+Tab leave a drilled pane first and + * otherwise close back to the trigger. A drilled pane hands focus to the row + * of the value in use, and returning to the root pane hands it back to the + * cell that opened it. Data and submission ride the SAME per-session + * ModelDirectory as the /model popup; exact-model reasoning metadata and the + * selected effort come from the Host rather than a client-owned vocabulary. A + * rejected selection announces through the shared transient Toast anchored to + * the composer card; the in-menu strip with Retry remains the catalog-load + * surface. */ import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, @@ -123,6 +129,27 @@ export function ModelSelect( return () => { document.removeEventListener('mousedown', closeOutside) } }, [open]) + // A pane switch unmounts the row that had focus, which drops focus onto the + // page body — outside the card's subtree, where its key handling no longer + // sees a keystroke. Every switch therefore names where the keyboard lands: + // drilling on the pane's current value, coming back on the cell that opened + // the pane left. + const paneFocus = useRef<'drill' | 'model' | 'effort' | null>(null) + useEffect(() => { + const intent = paneFocus.current + paneFocus.current = null + if (!open || intent === null) return + if (intent === 'drill') { + // The checked row is the value in use; a pane without one opens on its + // first row. + const checked = menuRef.current?.querySelector('[role="menuitemradio"][aria-checked="true"]') + const target = checked ?? itemRefs.current.find(item => item !== null) + target?.focus() + return + } + itemRefs.current[intent === 'effort' ? 1 : 0]?.focus() + }, [open, pane]) + // Portaled placement (the Menu primitive's portal rules: fixed from the // anchor rect, measured before paint, clamped inside the viewport): above // the trigger, right edges aligned. Depends on pane and directory state @@ -171,11 +198,27 @@ export function ModelSelect( if (restoreFocus) queueMicrotask(() => { triggerRef.current?.focus() }) } + const drill = (next: Pane): void => { + paneFocus.current = 'drill' + setPane(next) + } + + /** Leave a drilled pane for the root one, handing the keyboard back to its cell. */ + const back = (from: Exclude): void => { + paneFocus.current = from + setPane('root') + } + const moveFocus = (offset: number): void => { const items = itemRefs.current.filter(item => item !== null) if (items.length === 0) return const active = items.findIndex(item => item === document.activeElement) - const next = (Math.max(active, 0) + offset + items.length) % items.length + // Focus outside the rows (the trigger, which keeps it while the menu + // opens) enters at the end the step comes from: the first row forward, + // the last row backward. + const next = active === -1 + ? (offset > 0 ? 0 : items.length - 1) + : (active + offset + items.length) % items.length items[next]?.focus() } @@ -183,11 +226,32 @@ export function ModelSelect( if (event.key === 'Escape' && open) { event.preventDefault() // Escape backs out of a drilled pane first, then closes. - if (pane !== 'root') setPane('root') + if (pane !== 'root') back(pane) else close(true) return } if (!open) return + // Tab settles like Enter and Shift+Tab leaves like Escape, so the menu's + // keys mean what they mean in the composer. Both are consumed: the card + // keeps the browser's focus traversal out while it is open. + if (event.key === 'Tab') { + event.preventDefault() + if (event.shiftKey) { + if (pane !== 'root') back(pane) + else close(true) + return + } + // Settling activates the row the keyboard is on; with focus still on the + // trigger, Tab enters the menu at the value in use instead. + const focused = document.activeElement + if (focused instanceof HTMLElement && menuRef.current?.contains(focused) === true) { + focused.click() + return + } + const checked = menuRef.current?.querySelector('[role="menuitemradio"][aria-checked="true"]') + ;(checked ?? itemRefs.current.find(item => item !== null))?.focus() + return + } if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { event.preventDefault() moveFocus(event.key === 'ArrowDown' ? 1 : -1) @@ -299,13 +363,13 @@ export function ModelSelect( > {pane === 'root' && ( <> - {reasoning !== undefined && ( - } items={items} onSelect={onSelect} onClose={onClose} />) + // autoFocus parks the keyboard on the first row; Tab settles it like Enter. + const alpha = screen.getByRole('menuitem', { name: 'Alpha' }) + expect(document.activeElement).toBe(alpha) + expect(fireEvent.keyDown(alpha, { key: 'Tab' })).toBe(false) + expect(onSelect).toHaveBeenCalledExactlyOnceWith('a') + + // Shift+Tab leaves like Escape: closed, with the trigger taking the keyboard. + fireEvent.keyDown(alpha, { key: 'Tab', shiftKey: true }) + expect(onClose).toHaveBeenCalledTimes(1) + expect(document.activeElement).toBe(screen.getByRole('button', { name: 'trigger' })) + }) + + it('Tab from the trigger enters the open list, and elsewhere on the page stays native', () => { + render( + trigger} items={items} onSelect={() => {}} onClose={() => {}} />) + const trigger = screen.getByRole('button', { name: 'trigger' }) + trigger.focus() + expect(fireEvent.keyDown(trigger, { key: 'Tab' })).toBe(false) + expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: 'Alpha' })) + + // A keyboard outside both the anchor and the list keeps the traversal. + const outside = document.createElement('button') + document.body.append(outside) + outside.focus() + expect(fireEvent.keyDown(outside, { key: 'Tab' })).toBe(true) + outside.remove() + }) + + it('walks the list with the arrows without autoFocus, wrapping at both ends', () => { + const onClose = vi.fn() + const rows = [ + { id: 'a', label: 'Alpha' }, + { id: 'b', label: 'Beta' }, + { id: 'c', label: 'Gamma' }, + ] + render( + trigger} items={rows} onSelect={() => {}} onClose={onClose} />) + const trigger = screen.getByRole('button', { name: 'trigger' }) + const alpha = screen.getByRole('menuitem', { name: 'Alpha' }) + const beta = screen.getByRole('menuitem', { name: 'Beta' }) + const gamma = screen.getByRole('menuitem', { name: 'Gamma' }) + trigger.focus() + // autoFocus is off: the menu opens with the keyboard on the anchor, and the + // first step enters at the near end. + expect(document.activeElement).toBe(trigger) + expect(fireEvent.keyDown(trigger, { key: 'ArrowDown' })).toBe(false) + expect(document.activeElement).toBe(alpha) + fireEvent.keyDown(alpha, { key: 'ArrowDown' }) + fireEvent.keyDown(beta, { key: 'ArrowDown' }) + expect(document.activeElement).toBe(gamma) + fireEvent.keyDown(gamma, { key: 'ArrowDown' }) // wraps forwards + expect(document.activeElement).toBe(alpha) + fireEvent.keyDown(alpha, { key: 'ArrowUp' }) // wraps backwards + expect(document.activeElement).toBe(gamma) + fireEvent.keyDown(gamma, { key: 'Home' }) + expect(document.activeElement).toBe(alpha) + fireEvent.keyDown(alpha, { key: 'End' }) + expect(document.activeElement).toBe(gamma) + // Escape closes and hands the keyboard back to the anchor. + fireEvent.keyDown(gamma, { key: 'Escape' }) + expect(onClose).toHaveBeenCalledTimes(1) + expect(document.activeElement).toBe(trigger) + }) + + it('enters at the last enabled row on ↑ and steps over a disabled one', () => { + render( + trigger} items={items} onSelect={() => {}} onClose={() => {}} />) + const trigger = screen.getByRole('button', { name: 'trigger' }) + trigger.focus() + // Beta is disabled: it is not a step target, so Alpha is the only row. + expect(fireEvent.keyDown(trigger, { key: 'ArrowUp' })).toBe(false) + expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: 'Alpha' })) + }) + + it('leaves Escape to a menu open inside the dialog, then closes on the next one', () => { + const onClose = vi.fn() + const onSelect = vi.fn() + function Host() { + const [menuOpen, setMenuOpen] = useState(false) + return ( + + { setMenuOpen(true) }}>permissions} + items={[{ id: 'a', label: 'Alpha' }]} + onSelect={onSelect} + onClose={() => { setMenuOpen(false) }} + /> + + ) + } + render() + fireEvent.click(screen.getByRole('button', { name: 'permissions' })) + expect(screen.getByRole('menu')).toBeTruthy() + + // The menu is the inner layer: its Escape closes it and keeps the dialog. + fireEvent.keyDown(document, { key: 'Escape' }) + expect(screen.queryByRole('menu')).toBeNull() + expect(onClose).not.toHaveBeenCalled() + expect(screen.getByRole('dialog', { name: 'Settings' })).toBeTruthy() + + // With no menu open, the next Escape reaches the dialog. + fireEvent.keyDown(document, { key: 'Escape' }) + expect(onClose).toHaveBeenCalledTimes(1) + }) + + it('resumes the arrow walk after focus left the rows instead of re-entering', () => { + const rows = [ + { id: 'a', label: 'Alpha' }, + { id: 'b', label: 'Beta' }, + { id: 'c', label: 'Gamma' }, + ] + render( + trigger} items={rows} onSelect={() => {}} onClose={() => {}} />) + const trigger = screen.getByRole('button', { name: 'trigger' }) + const alpha = screen.getByRole('menuitem', { name: 'Alpha' }) + const beta = screen.getByRole('menuitem', { name: 'Beta' }) + trigger.focus() + fireEvent.keyDown(trigger, { key: 'ArrowDown' }) + fireEvent.keyDown(alpha, { key: 'ArrowDown' }) + expect(document.activeElement).toBe(beta) + + // Focus leaves the rows — a portal frame that refused focus, a detached + // node. The next step must resume from Beta, not re-enter at the far end + // (which would alternate between the first and last row forever). + trigger.focus() + fireEvent.keyDown(trigger, { key: 'ArrowUp' }) + expect(document.activeElement).toBe(alpha) + }) + + it('returns the keyboard to the anchor after a row is selected', () => { + const onSelect = vi.fn() + render( + trigger} items={items} onSelect={onSelect} onClose={() => {}} />) + const alpha = screen.getByRole('menuitem', { name: 'Alpha' }) + // autoFocus parked the keyboard on the first row; selecting unmounts the + // rows with the list in the real consumers, so the anchor takes it back. + expect(document.activeElement).toBe(alpha) + fireEvent.click(alpha) + expect(onSelect).toHaveBeenCalledWith('a') + expect(document.activeElement).toBe(screen.getByRole('button', { name: 'trigger' })) + }) + it('renders a non-interactive heading label and a danger row', () => { const onSelect = vi.fn() render( diff --git a/packages/client/ui-settings-general/src/client/SettingsRoot.tsx b/packages/client/ui-settings-general/src/client/SettingsRoot.tsx index 33ad30cb1b..0100531990 100644 --- a/packages/client/ui-settings-general/src/client/SettingsRoot.tsx +++ b/packages/client/ui-settings-general/src/client/SettingsRoot.tsx @@ -57,7 +57,10 @@ function SettingsPanel({ rows, renderSlot, activeId, onSelect, onClose }: PanelP useEffect(() => { const onKeyDown = (e: KeyboardEvent) => { - if (e.key === 'Escape') onClose() + // A row's open menu is an inner layer: its own Escape closes it, and the + // panel waits for the next one. + if (e.key !== 'Escape' || document.querySelector('[role="menu"]') !== null) return + onClose() } document.addEventListener('keydown', onKeyDown) return () => { document.removeEventListener('keydown', onKeyDown) } diff --git a/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx b/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx index 9a83b4274d..5fc6f0b092 100644 --- a/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx +++ b/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx @@ -268,6 +268,23 @@ describe('SettingsPanel close paths', () => { await vi.waitFor(() => { expect(document.activeElement).toBe(trigger) }) }) + it('leaves Escape to a menu open inside the panel, then closes on the next one', async () => { + mount() + const trigger = openPanel() + // The guard's condition is the open menu's marker, which a row's dropdown + // renders inside the panel. + const menu = document.createElement('div') + menu.setAttribute('role', 'menu') + screen.getByRole('dialog').append(menu) + fireEvent.keyDown(document, { key: 'Escape' }) + expect(screen.getByRole('dialog')).toBeTruthy() + + menu.remove() + fireEvent.keyDown(document, { key: 'Escape' }) + expect(screen.queryByRole('dialog')).toBeNull() + await vi.waitFor(() => { expect(document.activeElement).toBe(trigger) }) + }) + it('closes via document-level Escape, restores trigger focus, and unhooks the listener', async () => { mount() const trigger = openPanel() From 4b8a47a1987c38b56e04d1fc6dec905943ad0f47 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Tue, 15 Sep 2026 13:38:56 +0800 Subject: [PATCH 03/13] docs(client): record the SessionInput focus addition in the note --- .../feature/2026-09-14-composer-selection-keyboard.i18n.yaml | 4 ++-- .../feature/2026-09-14-composer-selection-keyboard.md | 2 +- .../feature/2026-09-14-composer-selection-keyboard.zh.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.i18n.yaml b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.i18n.yaml index 603357d9af..3e0b74d5e6 100644 --- a/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.md -2026-09-14-composer-selection-keyboard.md: da5c7267bf5506024183e11271dd20357f351104 -2026-09-14-composer-selection-keyboard.zh.md: 0723b390a9cf4abe38322149a06d768d808787d3 +2026-09-14-composer-selection-keyboard.md: 50802a03cb2f0fee75bcdb62169c2b33ce5690ec +2026-09-14-composer-selection-keyboard.zh.md: daa2c999e43f9ccf1acdd7ee2ad2e7115838eec1 diff --git a/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.md b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.md index da5c7267bf..50802a03cb 100644 --- a/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.md +++ b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.md @@ -14,7 +14,7 @@ The model seat's dropdown (`ModelSelect`, whose Effort row opens the reasoning-l ## Decision -`PopupSelectView` settles on Enter or Tab and leaves on Escape or Shift+Tab: Enter and Tab both run `select` on the filtered highlight, Escape and Shift+Tab both dismiss and return focus to the composer through the conversation's own `focus()`, which rides Lexical so the caret comes back where the draft left it rather than at the start. Opening the trigger menu from the composer's launcher button does the same before the menu opens: the menu is a combobox over the editor, so the button cannot hold the keyboard. `↑`/`↓` walk the filtered highlight (wrapping, scrolled into view) and `←`/`→` stay native to the search input. Every one of those keys is consumed, so a row list that is not ready yet swallows Tab as a no-op rather than releasing focus out of the card. +`PopupSelectView` settles on Enter or Tab and leaves on Escape or Shift+Tab: Enter and Tab both run `select` on the filtered highlight, Escape and Shift+Tab both dismiss and return focus to the composer through the conversation's own `focus()`, which rides Lexical so the caret comes back where the draft left it rather than at the start. That method is the one addition this decision makes to the `SessionInput` face: the shell needs the composer's own focus, not a DOM focus on its contenteditable, and the owner of the caret is the only party that can restore it. Opening the trigger menu from the composer's launcher button does the same before the menu opens: the menu is a combobox over the editor, so the button cannot hold the keyboard. `↑`/`↓` walk the filtered highlight (wrapping, scrolled into view) and `←`/`→` stay native to the search input. Every one of those keys is consumed, so a row list that is not ready yet swallows Tab as a no-op rather than releasing focus out of the card. `PopupSelectController` parks the highlight on the row the loaded list marks as the current value, falling back to the top row when no row is marked or when the search retained across a retry hides it. Typing rebases the highlight to the top of the filtered rows, because a search asks for something other than the current value. Settling on a freshly opened panel therefore confirms the value in use. diff --git a/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.zh.md b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.zh.md index 0723b390a9..daa2c999e4 100644 --- a/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.zh.md +++ b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.zh.md @@ -14,7 +14,7 @@ composer 内有两个选择界面在打开期间持有焦点,两者都把 Tab ## 决策 -`PopupSelectView` 用回车或 Tab 接受,用 Escape 或 Shift+Tab 离开:回车与 Tab 都对筛选后的高亮行执行 `select`,Escape 与 Shift+Tab 都关闭并通过对话自己的 `focus()` 把焦点还给 composer,该路径走 Lexical,因此光标回到草稿原来的位置,而不是开头。从 composer 的 launcher 按钮打开触发菜单时也在开菜单之前做同样的事:该菜单是挂在编辑器上的 combobox,按钮不能握着键盘。`↑`/`↓` 在筛选后的高亮间移动(循环,滚动进视野),`←`/`→` 仍归搜索框的原生光标。上述按键全部被消费,因此尚未就绪的行列表会把 Tab 当作 no-op 吞掉,而不是把焦点放出卡片。 +`PopupSelectView` 用回车或 Tab 接受,用 Escape 或 Shift+Tab 离开:回车与 Tab 都对筛选后的高亮行执行 `select`,Escape 与 Shift+Tab 都关闭并通过对话自己的 `focus()` 把焦点还给 composer,该路径走 Lexical,因此光标回到草稿原来的位置,而不是开头。该方法是本决策对 `SessionInput` 面的唯一新增:外壳需要的是 composer 自己的焦点,而不是对其 contenteditable 的 DOM focus,而光标的拥有者是唯一能恢复它的一方。从 composer 的 launcher 按钮打开触发菜单时也在开菜单之前做同样的事:该菜单是挂在编辑器上的 combobox,按钮不能握着键盘。`↑`/`↓` 在筛选后的高亮间移动(循环,滚动进视野),`←`/`→` 仍归搜索框的原生光标。上述按键全部被消费,因此尚未就绪的行列表会把 Tab 当作 no-op 吞掉,而不是把焦点放出卡片。 `PopupSelectController` 把高亮停在已加载列表标记为当前值的那一行;没有行被标记,或重试时保留的搜索把该行过滤掉时,退回首行。输入搜索会把高亮重定到筛选结果的首行,因为搜索要找的正是当前值之外的东西。因此在刚打开的面板上接受即确认正在使用的值。 From 449a4610d7fe906a69ca3e666dbd008d4d62ece2 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Tue, 15 Sep 2026 13:52:49 +0800 Subject: [PATCH 04/13] fix(client): keep the browser ring on the focused menu row The menu family was the only place that suppressed the browser's default focus ring. It keeps that ring now, like the app's other controls, on top of the hover fill a walked row already carried. --- packages/client/ui-primitives/src/Menu.module.css | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/packages/client/ui-primitives/src/Menu.module.css b/packages/client/ui-primitives/src/Menu.module.css index 29f985b00b..fd61361bb6 100644 --- a/packages/client/ui-primitives/src/Menu.module.css +++ b/packages/client/ui-primitives/src/Menu.module.css @@ -117,12 +117,10 @@ } /* Arrow navigation moves real focus, so the row the keyboard is on carries the - same fill the pointer gets: without it nothing shows which row is current. - The fill replaces the browser's default ring — the composer's other triggers - suppress theirs the same way — so no blue outline frames the row. */ + same fill the pointer gets on top of the browser's own focus ring, which the + app's other controls keep too. */ .item:focus-visible:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); - outline: none; } .denseList .item { @@ -219,7 +217,6 @@ .danger:focus-visible:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover-danger); - outline: none; } /* Heading row: non-interactive small grey text, padding aligned with items. */ From 4fc515cb6802c957b9794584498ff7d6fb0ef91e Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Tue, 15 Sep 2026 13:55:50 +0800 Subject: [PATCH 05/13] fix(client): keep the ring on the triggers and off the menu rows The two split the other way around: the composer's triggers keep the focus ring their design gives them (a 2px `--dsw-alias-border-l3` ring), while a walked menu row shows the hover fill alone, without the browser's default outline doubling it. --- .../ui-model-selection/src/client/ModelSelect.module.css | 5 +---- .../src/client/PermissionSelect.module.css | 5 +---- packages/client/ui-primitives/src/Menu.module.css | 6 ++++-- 3 files changed, 6 insertions(+), 10 deletions(-) diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.module.css b/packages/client/ui-model-selection/src/client/ModelSelect.module.css index fdec30ecf3..b2cb715287 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.module.css +++ b/packages/client/ui-model-selection/src/client/ModelSelect.module.css @@ -34,10 +34,7 @@ } .trigger:focus-visible { - /* The same fill a hovered trigger gets: the trigger is one of the row-like - controls of the composer, and the ring its neighbours never drew read as a - different kind of state. */ - background: var(--dsw-alias-interactive-bg-hover); + box-shadow: 0 0 0 2px var(--dsw-alias-border-l3); } .trigger:disabled { diff --git a/packages/client/ui-permission-presets/src/client/PermissionSelect.module.css b/packages/client/ui-permission-presets/src/client/PermissionSelect.module.css index c7746273d1..32cc84dd14 100644 --- a/packages/client/ui-permission-presets/src/client/PermissionSelect.module.css +++ b/packages/client/ui-permission-presets/src/client/PermissionSelect.module.css @@ -23,10 +23,7 @@ } .trigger:focus-visible { - /* The same fill a hovered trigger gets: the trigger is one of the row-like - controls of the composer, and the ring its neighbours never drew read as a - different kind of state. */ - background: var(--dsw-alias-interactive-bg-hover); + box-shadow: 0 0 0 2px var(--dsw-alias-border-l3); } .trigger:disabled { diff --git a/packages/client/ui-primitives/src/Menu.module.css b/packages/client/ui-primitives/src/Menu.module.css index fd61361bb6..0525f2c6e4 100644 --- a/packages/client/ui-primitives/src/Menu.module.css +++ b/packages/client/ui-primitives/src/Menu.module.css @@ -117,10 +117,11 @@ } /* Arrow navigation moves real focus, so the row the keyboard is on carries the - same fill the pointer gets on top of the browser's own focus ring, which the - app's other controls keep too. */ + same fill the pointer gets: the fill is the row's focus indication, and the + browser's default ring would double it. */ .item:focus-visible:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); + outline: none; } .denseList .item { @@ -217,6 +218,7 @@ .danger:focus-visible:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover-danger); + outline: none; } /* Heading row: non-interactive small grey text, padding aligned with items. */ From 3065f9cc27e7074c629b1e4527d962518439a3ec Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Tue, 15 Sep 2026 13:59:38 +0800 Subject: [PATCH 06/13] docs(client): drop a reverted implementation from the note's evidence list --- .../feature/2026-09-14-composer-selection-keyboard.i18n.yaml | 4 ++-- .../feature/2026-09-14-composer-selection-keyboard.md | 2 +- .../feature/2026-09-14-composer-selection-keyboard.zh.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.i18n.yaml b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.i18n.yaml index 3e0b74d5e6..cc25662ea6 100644 --- a/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.md -2026-09-14-composer-selection-keyboard.md: 50802a03cb2f0fee75bcdb62169c2b33ce5690ec -2026-09-14-composer-selection-keyboard.zh.md: daa2c999e43f9ccf1acdd7ee2ad2e7115838eec1 +2026-09-14-composer-selection-keyboard.md: 9d7f8da91bc69b333ab690a32ea74e219961b6e9 +2026-09-14-composer-selection-keyboard.zh.md: c86e42857f66ff5efb0c6a57dce46e3df79cda0c diff --git a/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.md b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.md index 50802a03cb..9d7f8da91b 100644 --- a/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.md +++ b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.md @@ -42,7 +42,7 @@ The row contracts are unchanged. Producers already mark their current row `activ ## Verification -[Seat browser evidence](../../../../apps/web/tests/declared-reasoning.e2e.ts) drives a real Chromium against the shipped bundles: it opens the drilled level pane, walks it with `↑`, settles a level with Tab and asserts the saved effort, then reopens the pane and asserts the keyboard lands on that level rather than the top of the list before Shift+Tab walks back to the drilled cell and closes. [Seat keyboard tests](../../../../packages/client/ui-model-selection/tests/model-select.client.spec.tsx) cover the drilled-pane handoff onto the value in use (and onto the first row when no row is marked), the handoff back onto the cell, the `↑`/`↓` walk with both wraps, Tab settling a focused row and entering the menu from the trigger, Shift+Tab leaving a pane then closing, and Tab staying native while the menu is closed. [Popup view tests](../../../../packages/client/ui-commands/tests/popup-view.client.spec.tsx) cover the shell binding the composer input of its own card, Tab settling the parked highlight with consumption and refocus, Shift+Tab dismissing without settling, Tab consumed while rows load without leaving the card, the arrows staying distinct from the native left/right caret, and the wrap on `↑`/`↓`. [Trigger tests](../../../../packages/client/ui-input-trigger/tests/service.client.spec.ts) cover a dismissal sticking to its hit (Escape, a pointer dismissal, and a settling pick), the same hit re-tracking closed, and a changed query re-arming the menu. [Menu tests](../../../../packages/client/ui-primitives/tests/atoms.client.spec.tsx) cover the arrow walk without `autoFocus` (entering at the near end, wrapping, and stepping over a disabled row), Escape returning focus to the anchor, Tab settling the focused row, Shift+Tab closing back to the anchor, Tab entering the list from the anchor, and an unrelated Tab staying native while the list is open. [Popup controller tests](../../../../packages/client/ui-commands/tests/popup.client.spec.ts) cover the parked highlight, its top-row fallback without a marked row, the re-park inside a search retained across a retry, and the rebase to the top row on typing. The popup panel's Tab has unit coverage only: no Web scenario drives `/model` or `/permission` yet. +[Seat browser evidence](../../../../apps/web/tests/declared-reasoning.e2e.ts) drives a real Chromium against the shipped bundles: it opens the drilled level pane, walks it with `↑`, settles a level with Tab and asserts the saved effort, then reopens the pane and asserts the keyboard lands on that level rather than the top of the list before Shift+Tab walks back to the drilled cell and closes. [Seat keyboard tests](../../../../packages/client/ui-model-selection/tests/model-select.client.spec.tsx) cover the drilled-pane handoff onto the value in use (and onto the first row when no row is marked), the handoff back onto the cell, the `↑`/`↓` walk with both wraps, Tab settling a focused row and entering the menu from the trigger, Shift+Tab leaving a pane then closing, and Tab staying native while the menu is closed. [Popup view tests](../../../../packages/client/ui-commands/tests/popup-view.client.spec.tsx) cover Tab settling the parked highlight with consumption and refocus, Shift+Tab dismissing without settling, Tab consumed while rows load without leaving the card, the arrows staying distinct from the native left/right caret, and the wrap on `↑`/`↓`. [Trigger tests](../../../../packages/client/ui-input-trigger/tests/service.client.spec.ts) cover a dismissal sticking to its hit (Escape, a pointer dismissal, and a settling pick), the same hit re-tracking closed, and a changed query re-arming the menu. [Menu tests](../../../../packages/client/ui-primitives/tests/atoms.client.spec.tsx) cover the arrow walk without `autoFocus` (entering at the near end, wrapping, and stepping over a disabled row), Escape returning focus to the anchor, Tab settling the focused row, Shift+Tab closing back to the anchor, Tab entering the list from the anchor, and an unrelated Tab staying native while the list is open. [Popup controller tests](../../../../packages/client/ui-commands/tests/popup.client.spec.ts) cover the parked highlight, its top-row fallback without a marked row, the re-park inside a search retained across a retry, and the rebase to the top row on typing. The popup panel's Tab has unit coverage only: no Web scenario drives `/model` or `/permission` yet. ## Consequences diff --git a/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.zh.md b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.zh.md index daa2c999e4..c86e42857f 100644 --- a/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.zh.md +++ b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.zh.md @@ -42,7 +42,7 @@ composer 内有两个选择界面在打开期间持有焦点,两者都把 Tab ## 验证 -[模型位浏览器证据](../../../../apps/web/tests/declared-reasoning.e2e.ts) 用真实 Chromium 驱动已发布的 bundle:打开已下钻的等级面板,用 `↑` 走位,用 Tab 选定一档并断言保存下来的推理等级,随后重新打开该面板、断言键盘落在那一档而不是列表顶部,再用 Shift+Tab 退回被下钻的格子并关闭。[模型位键盘测试](../../../../packages/client/ui-model-selection/tests/model-select.client.spec.tsx) 覆盖下钻交接落在正在使用的值上(没有标记行时落在首行)、交回给该格子、`↑`/`↓` 的双向循环走位、Tab 选定聚焦行以及从触发器进入菜单、Shift+Tab 先退层再关闭,以及菜单关闭时 Tab 保持原生。[弹窗视图测试](../../../../packages/client/ui-commands/tests/popup-view.client.spec.tsx) 覆盖外壳绑定自己卡片内的 composer 输入框、 Tab 接受停放的高亮并完成消费与焦点归还、Shift+Tab 关闭且不接受、行仍在加载时 Tab 被消费且焦点不离开卡片、方向键与原生左右光标互不干扰,以及 `↑`/`↓` 的循环。[触发流水线测试](../../../../packages/client/ui-input-trigger/tests/service.client.spec.ts) 覆盖关闭粘在它自己的命中上(Escape、指针关闭、落定选定三种)、同一命中重新 track 时保持关闭,以及查询改变后菜单重新武装。[Menu 测试](../../../../packages/client/ui-primitives/tests/atoms.client.spec.tsx) 覆盖不带 `autoFocus` 的方向键走位(从近端进入、两端循环、跳过禁用行)、Escape 把焦点还给锚点、Tab 选定聚焦行、Shift+Tab 关闭并把焦点还给锚点、Tab 从锚点进入列表,以及列表打开期间无关位置的 Tab 保持原生。[弹窗控制器测试](../../../../packages/client/ui-commands/tests/popup.client.spec.ts) 覆盖高亮的停放、没有标记行时退回首行、重试时在保留的搜索内重新停放,以及输入时重定到首行。弹窗面板的 Tab 只有单元覆盖:目前还没有 Web 场景驱动 `/model` 或 `/permission`。 +[模型位浏览器证据](../../../../apps/web/tests/declared-reasoning.e2e.ts) 用真实 Chromium 驱动已发布的 bundle:打开已下钻的等级面板,用 `↑` 走位,用 Tab 选定一档并断言保存下来的推理等级,随后重新打开该面板、断言键盘落在那一档而不是列表顶部,再用 Shift+Tab 退回被下钻的格子并关闭。[模型位键盘测试](../../../../packages/client/ui-model-selection/tests/model-select.client.spec.tsx) 覆盖下钻交接落在正在使用的值上(没有标记行时落在首行)、交回给该格子、`↑`/`↓` 的双向循环走位、Tab 选定聚焦行以及从触发器进入菜单、Shift+Tab 先退层再关闭,以及菜单关闭时 Tab 保持原生。[弹窗视图测试](../../../../packages/client/ui-commands/tests/popup-view.client.spec.tsx) 覆盖 Tab 接受停放的高亮并完成消费与焦点归还、Shift+Tab 关闭且不接受、行仍在加载时 Tab 被消费且焦点不离开卡片、方向键与原生左右光标互不干扰,以及 `↑`/`↓` 的循环。[触发流水线测试](../../../../packages/client/ui-input-trigger/tests/service.client.spec.ts) 覆盖关闭粘在它自己的命中上(Escape、指针关闭、落定选定三种)、同一命中重新 track 时保持关闭,以及查询改变后菜单重新武装。[Menu 测试](../../../../packages/client/ui-primitives/tests/atoms.client.spec.tsx) 覆盖不带 `autoFocus` 的方向键走位(从近端进入、两端循环、跳过禁用行)、Escape 把焦点还给锚点、Tab 选定聚焦行、Shift+Tab 关闭并把焦点还给锚点、Tab 从锚点进入列表,以及列表打开期间无关位置的 Tab 保持原生。[弹窗控制器测试](../../../../packages/client/ui-commands/tests/popup.client.spec.ts) 覆盖高亮的停放、没有标记行时退回首行、重试时在保留的搜索内重新停放,以及输入时重定到首行。弹窗面板的 Tab 只有单元覆盖:目前还没有 Web 场景驱动 `/model` 或 `/permission`。 ## 影响 From 5c3081eeaa95968854aa59acfb45a40765692bbc Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Tue, 15 Sep 2026 14:16:14 +0800 Subject: [PATCH 07/13] fix(client): tighten the keyboard hand-offs, and drop the dialog Escape layering Review follow-ups on the hand-offs this branch added: - Menu gives the keyboard back to the control that opened it (an anchor may wrap several, as a split button does), falls back to a disabled-free anchor button, leaves a Tab it cannot use to the browser, and no longer moves focus while the owner keeps the list open. - The model seat settles only real rows with Tab and keeps the keyboard on its trigger when a pane's rows are disabled or absent. - The popup shell leaves Tab to the browser when nothing can be settled (the error strip's retry button stays reachable), and a dismissal caused by a stale catalog returns the keyboard like the other paths. - A frozen-tier track is the submit gesture's own bookkeeping and no longer re-arms a menu the user dismissed. - The launcher reuses the shared caret-preserving focus helper; the option contract records that `active` is the row an accept gesture confirms; the conversation README documents the composer's key and focus behavior. The dialog/menu Escape layering this branch also carried is out of scope here and has been removed again. --- ...26-09-15-overlay-escape-layering.i18n.yaml | 6 -- .../2026-09-15-overlay-escape-layering.md | 29 ------- .../2026-09-15-overlay-escape-layering.zh.md | 29 ------- .../src/client/PopupSelectView.tsx | 4 + .../client/ui-commands/src/client/contract.ts | 6 ++ .../client/ui-commands/src/client/service.ts | 5 +- .../tests/popup-view.client.spec.tsx | 5 +- .../ui-commands/tests/service.client.spec.ts | 3 +- .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 2 +- packages/client/ui-conversation/README.zh.md | 2 +- .../src/client/skeleton/InputBar.tsx | 2 +- .../ui-input-trigger/src/client/controller.ts | 5 +- .../src/client/ModelSelect.tsx | 18 +++-- .../tests/model-select.client.spec.tsx | 12 ++- .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 2 +- packages/client/ui-primitives/README.zh.md | 2 +- packages/client/ui-primitives/src/Menu.tsx | 79 ++++++++++++++----- packages/client/ui-primitives/src/Modal.tsx | 5 +- .../ui-primitives/tests/atoms.client.spec.tsx | 70 ---------------- .../src/client/SettingsRoot.tsx | 5 +- .../tests/settings-root.client.spec.tsx | 17 ---- 23 files changed, 117 insertions(+), 199 deletions(-) delete mode 100644 .agents/notes/implemented/bug-fix/2026-09-15-overlay-escape-layering.i18n.yaml delete mode 100644 .agents/notes/implemented/bug-fix/2026-09-15-overlay-escape-layering.md delete mode 100644 .agents/notes/implemented/bug-fix/2026-09-15-overlay-escape-layering.zh.md diff --git a/.agents/notes/implemented/bug-fix/2026-09-15-overlay-escape-layering.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-09-15-overlay-escape-layering.i18n.yaml deleted file mode 100644 index e4d35b7cd6..0000000000 --- a/.agents/notes/implemented/bug-fix/2026-09-15-overlay-escape-layering.i18n.yaml +++ /dev/null @@ -1,6 +0,0 @@ -# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each -# side as of the last confirmed-consistent state. Both languages carry equal authority; -# after editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-09-15-overlay-escape-layering.md -2026-09-15-overlay-escape-layering.md: 6a8e2affca2f1150fd0746bd63b242472d88e2cf -2026-09-15-overlay-escape-layering.zh.md: 78e395b62bc2e69f394117b0a5b96aadf94950e9 diff --git a/.agents/notes/implemented/bug-fix/2026-09-15-overlay-escape-layering.md b/.agents/notes/implemented/bug-fix/2026-09-15-overlay-escape-layering.md deleted file mode 100644 index 6a8e2affca..0000000000 --- a/.agents/notes/implemented/bug-fix/2026-09-15-overlay-escape-layering.md +++ /dev/null @@ -1,29 +0,0 @@ -# Agent Note: An open menu takes the first Escape from its dialog - -Status: implemented - -English | [中文](2026-09-15-overlay-escape-layering.zh.md) - -## Problem - -`Modal` and `Menu` each close on Escape through their own document-level keydown listener. A menu open inside a dialog is therefore closed by the same keystroke that closes the dialog: one Escape discards two layers of the user's context and leaves the keyboard wherever it was before the dialog opened. Every settings row, the workspace browser, and the terminal body render a menu inside a dialog. - -## Decision - -The dialog yields the first Escape to an open menu. `Modal`'s keydown listener returns while `document.querySelector('[role="menu"]')` matches, so the menu's own handler closes the menu and returns the keyboard to its anchor; the next Escape reaches the dialog. Menus that render no `[role="menu"]` — the composer's trigger menu and popup select panel are listboxes — keep their own layering and are unaffected. - -## Alternatives considered - -**Order the two listeners.** Both sit on `document`, so which runs first is registration order: a dialog mounts before the menu it opens, so the dialog always wins. Making that order carry the rule would be fragile. - -**Track an overlay stack in a service.** Two nested layers in one place do not justify the machinery, and nothing else needs the ordering. - -**Let one Escape close both.** It is the behavior this decision removes: a single keystroke must not discard both the menu and the dialog the user opened it from. - -## Verification - -[Dialog tests](../../../../packages/client/ui-primitives/tests/atoms.client.spec.tsx) render a `Menu` inside an open `Modal`: the first Escape closes the menu and leaves the dialog standing with the keyboard on the menu's anchor, and the second Escape reaches the dialog. - -## Consequences - -Escape now walks the overlay layers one at a time: menu, then dialog. The dialog's own Escape keeps closing it directly when no menu is open inside it, and a menu that is not a `[role="menu"]` never intercepts the dialog's Escape. diff --git a/.agents/notes/implemented/bug-fix/2026-09-15-overlay-escape-layering.zh.md b/.agents/notes/implemented/bug-fix/2026-09-15-overlay-escape-layering.zh.md deleted file mode 100644 index 78e395b62b..0000000000 --- a/.agents/notes/implemented/bug-fix/2026-09-15-overlay-escape-layering.zh.md +++ /dev/null @@ -1,29 +0,0 @@ -# Agent Note: 打开的菜单从所在对话框手中接管第一次 Escape - -Status: implemented - -[English](2026-09-15-overlay-escape-layering.md) | 中文 - -## 问题 - -`Modal` 与 `Menu` 各自在 document 上挂 keydown 监听来响应 Escape。因此对话框内打开的菜单会被关闭对话框的同一次按键一并关掉:一次 Escape 丢掉用户上下文中的两层,并把键盘留在对话框打开前的位置。设置页的每一行、工作区浏览器与终端正文都会在对话框内渲染菜单。 - -## 决策 - -对话框把第一次 Escape 让给已打开的菜单。当 `document.querySelector('[role="menu"]')` 命中时,`Modal` 的 keydown 监听直接返回,于是菜单自己的处理关闭菜单并把焦点还给锚点;第二次 Escape 才到达对话框。不渲染 `[role="menu"]` 的菜单——composer 的触发菜单与 popupSelect 面板都是 listbox——保留各自的分层,不受影响。 - -## 备选方案 - -**给两个监听排顺序。** 两者都挂在 `document` 上,谁先执行取决于注册顺序:对话框先于它所打开的菜单挂载,因此永远是对话框先跑。把规则寄托在这个顺序上并不可靠。 - -**用服务维护一个浮层栈。** 只有一处两层嵌套,不值得为此引入机制,也没有其他调用方需要这个顺序。 - -**让一次 Escape 关掉两层。** 这正是本决策要消除的行为:一次按键不该丢掉用户打开的菜单与对话框两者。 - -## 验证 - -[对话框测试](../../../../packages/client/ui-primitives/tests/atoms.client.spec.tsx) 在打开的 `Modal` 内渲染一个 `Menu`:第一次 Escape 关闭菜单、对话框保持打开且键盘落在菜单锚点上,第二次 Escape 才到达对话框。 - -## 影响 - -Escape 现在逐层退出:先菜单,后对话框。对话框内没有菜单时,它自身的 Escape 仍直接关闭;不渲染 `[role="menu"]` 的菜单也永远不会拦下对话框的 Escape。 diff --git a/packages/client/ui-commands/src/client/PopupSelectView.tsx b/packages/client/ui-commands/src/client/PopupSelectView.tsx index 808b64340d..8ce2cc64a3 100644 --- a/packages/client/ui-commands/src/client/PopupSelectView.tsx +++ b/packages/client/ui-commands/src/client/PopupSelectView.tsx @@ -101,6 +101,10 @@ export function PopupSelectView({ popup, t }: PopupSelectViewProps) { // the shell HOLDS focus, and native traversal would leave an open card // whose search input lost focus. case 'Tab': + // With nothing to settle — still loading, failed, or filtered empty — + // the keystroke stays the browser's, which is how the error strip's + // retry button remains reachable. + if (!ev.shiftKey && (state.status !== 'ready' || rows.length === 0)) return ev.preventDefault() if (ev.shiftKey) popup.dismiss({ focusComposer: true }) else void popup.select(state.active) diff --git a/packages/client/ui-commands/src/client/contract.ts b/packages/client/ui-commands/src/client/contract.ts index 34d76e39fc..2ed58c7900 100644 --- a/packages/client/ui-commands/src/client/contract.ts +++ b/packages/client/ui-commands/src/client/contract.ts @@ -24,6 +24,12 @@ export interface SelectOption { /** Optional short marker rendered as a superscript beside the label. */ readonly badge?: string readonly detail?: string + /** + * The row the shell's highlight parks on when the panel opens, so an accept + * gesture made without looking confirms the value in use. A business package + * that marks a row `active` for presentation alone would make that row the + * default pick. + */ readonly active?: boolean /** Optional in-page risk gate owned by the shared popup shell. */ readonly confirmation?: SelectConfirmation diff --git a/packages/client/ui-commands/src/client/service.ts b/packages/client/ui-commands/src/client/service.ts index 055f5c3a00..49a7b5ce4d 100644 --- a/packages/client/ui-commands/src/client/service.ts +++ b/packages/client/ui-commands/src/client/service.ts @@ -148,7 +148,10 @@ export class CommandUiRuntime extends Service implements CommandUiContract { */ dismiss(name: string): void { for (const popup of this.live.popups.values()) { - if (popup.state.getSnapshot().command === name) popup.dismiss() + // A catalog that went stale underneath the card takes its rows away; the + // composer keeps the keyboard the card was holding, like every other + // dismissal path. + if (popup.state.getSnapshot().command === name) popup.dismiss({ focusComposer: true }) } } diff --git a/packages/client/ui-commands/tests/popup-view.client.spec.tsx b/packages/client/ui-commands/tests/popup-view.client.spec.tsx index 2dbfda9bb6..77b46dfa2e 100644 --- a/packages/client/ui-commands/tests/popup-view.client.spec.tsx +++ b/packages/client/ui-commands/tests/popup-view.client.spec.tsx @@ -146,12 +146,13 @@ describe('PopupSelectView', () => { expect(settling.view.container.childElementCount).toBe(0) }) - it('Tab is consumed while the rows are still loading: no pick, no focus escape', async () => { + it('Tab stays the browser\'s while the rows are still loading: no pick, no escape', async () => { const popup = new PopupSelectController({ consume: () => true, focusComposer: () => {} }) render() await act(async () => { popup.open('theme', spec({ options: () => new Promise(() => {}) }), 'ctx-A', SEGMENT) }) const search = screen.getByRole('textbox', { name: '筛选选项' }) - expect(fireEvent.keyDown(search, { key: 'Tab' })).toBe(false) + // Nothing is settleable yet, so the keystroke is not swallowed. + expect(fireEvent.keyDown(search, { key: 'Tab' })).toBe(true) expect(document.activeElement).toBe(search) expect(screen.getByText('正在加载选项…')).toBeTruthy() }) diff --git a/packages/client/ui-commands/tests/service.client.spec.ts b/packages/client/ui-commands/tests/service.client.spec.ts index 935c70440b..87d87311d7 100644 --- a/packages/client/ui-commands/tests/service.client.spec.ts +++ b/packages/client/ui-commands/tests/service.client.spec.ts @@ -991,7 +991,8 @@ describe('popupFor', () => { expect(second.state.getSnapshot()).toMatchObject({ open: false, options: [] }) expect(onSelect).not.toHaveBeenCalled() expect(consume).not.toHaveBeenCalled() - expect(focuses).toEqual([]) + // The stale catalog takes the rows away; the composer keeps the keyboard. + expect(focuses).toEqual([sid('s1'), sid('s2')]) }) it('resolves lazily per session; a foreign session gets its own controller; unscoped ctx throws', async () => { diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 1f20199505..0f694046e9 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md -README.md: 5b94862d830d27ae02e60832294c7595537b47c0 -README.zh.md: 6d7bb72ba582f90356f4bc08a78b2cdfdf211db7 +README.md: a82b40c5879e37eb4737b9d896787ba4bfdbc10c +README.zh.md: 342121dd45edc7412d27b94c8db837604f2b191f diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 5b94862d83..a82b40c587 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -50,7 +50,7 @@ View selection is deterministic: a registered persisted selection wins, otherwis The shell reads the persisted View preference before rendering when a Session first binds or a cached Session becomes current, activates the registered preferred View or Chat fallback, and activates later tab or focus selections before committing them to the store. A blank Session still omits the `conversation.view` slot; no unselected target is activated. -The resident composer survives no-Session and Session transitions. Whitespace hides its placeholder; a whitespace-only draft without attachments cannot be sent. The no-Session state keeps the same composer surface mounted but inert while the Workspace picker connects a blank Session. The surface is a shell-owned Lexical editor: reference chips are atomic decorator nodes carrying the owner's serialization identity (submission expands them through the owner codec), claimed slash commands stay styled leading text, folder text references carry the folder glyph as an icon prefix, and the draft's clipboard projection is mirrored into the per-Session Conversation store. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews render sent text through the shared inline reference projection from `ui-primitives` (wire session forms fold to their label) and show local or durable images and files in original attachment order. Images use thumbnails; files use compact name-and-size cards. An edit exposes the literal sent text, and durable thumbnails resolve through the session image URL cache. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace. +The resident composer survives no-Session and Session transitions. Whitespace hides its placeholder; a whitespace-only draft without attachments cannot be sent. The no-Session state keeps the same composer surface mounted but inert while the Workspace picker connects a blank Session. The surface is a shell-owned Lexical editor: reference chips are atomic decorator nodes carrying the owner's serialization identity (submission expands them through the owner codec), claimed slash commands stay styled leading text, folder text references carry the folder glyph as an icon prefix, and the draft's clipboard projection is mirrored into the per-Session Conversation store. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews render sent text through the shared inline reference projection from `ui-primitives` (wire session forms fold to their label) and show local or durable images and files in original attachment order. Images use thumbnails; files use compact name-and-size cards. An edit exposes the literal sent text, and durable thumbnails resolve through the session image URL cache. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace. The composer keymap arbitrates the trigger menu's keys through the slash pipeline — Tab settles the highlighted completion (or drills a drillable one), Escape and Shift+Tab leave the menu without settling — and leaves every other key to the editor. An overlay that takes the keyboard hands it back through `SessionInput.focus()`, which rides Lexical's own focus so the caret returns where the draft left it rather than at the start. Default sends commit optimistically: Enter clears the draft, occurrence table, and undo history in the same transaction, keeps the composer in `plain`, and runs the send as a detached attempt, so typing and further sends continue during the flight. `sendSession` registers a Session submission echo (`session.beginSubmission`) with the delivery mode before serializing, preserving selected image and file order in `pendingSubmissions`; Session derives the placement from that mode and its current running state, so idle sends use the transcript, busy Queue sends use QueueDock, and busy Steer sends use the pending-steering surface. It then yields one paint, encodes images through the browser's native `FileReader` data-URL path, and cites staged file receipts. Command submissions use the same receipts for generic files, so sending `/goal` or `/plan` never reads those browser files again. The prompt reuses the submission `requestId`; queue and history observation by that `rpcId` retires the echo once. Concurrent failures are restored together in submission order until the user edits the restored content; command submissions keep the frozen `submitting` phase. Detached attempts retain their attachment ids through admission and Session scope disposal. An observed retirement immediately exposes each image preview through the durable cache, replaces it with the canonical URL after fetching the admitted attachment, revokes each URL after its use ends, and releases file cards. Selected generic files enter one FIFO background-upload queue; `maxConcurrentFileUploads` defaults to two active Worker transports, the Conversation service retains queued and active operations plus byte progress across Session navigation, and removing a draft skips its queued transfer or aborts its active transport. Continuable subagents disable attachment intake and skip local echoes because their transport does not preserve the browser request id. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index 6d7bb72ba5..342121dd45 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -50,7 +50,7 @@ View 选择规则固定:有效且已注册的持久化选择优先,其次是 Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染前读取持久化 View 偏好,激活已注册的偏好 View 或 Chat fallback,并在后续 tab 或 focus 选择写入 store 前先激活对应 target。blank Session 仍不渲染 `conversation.view` slot;未选中的 target 不会激活。 -常驻 composer 在无 Session 与有 Session 之间保持挂载。输入空白字符会隐藏占位提示;没有附件的纯空白草稿无法发送。无 Session 时,同一个编辑器表面保持 inert,Workspace picker 连接 blank Session。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 保持为带样式的行首文本,文件夹文本引用以图标前缀携带文件夹图形,草稿的剪贴板投影镜像到逐 Session Conversation store。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览经 `ui-primitives` 的共享行内引用投影渲染已发送文本(wire 会话形式折叠为其标签),并按原始附件顺序展示本地或持久化的图片和文件。图片使用缩略图,文件使用紧凑的名称与大小卡片。编辑态展示字面发送文本,持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。 +常驻 composer 在无 Session 与有 Session 之间保持挂载。输入空白字符会隐藏占位提示;没有附件的纯空白草稿无法发送。无 Session 时,同一个编辑器表面保持 inert,Workspace picker 连接 blank Session。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 保持为带样式的行首文本,文件夹文本引用以图标前缀携带文件夹图形,草稿的剪贴板投影镜像到逐 Session Conversation store。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览经 `ui-primitives` 的共享行内引用投影渲染已发送文本(wire 会话形式折叠为其标签),并按原始附件顺序展示本地或持久化的图片和文件。图片使用缩略图,文件使用紧凑的名称与大小卡片。编辑态展示字面发送文本,持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。composer 键盘映射经斜杠流水线裁决触发菜单的按键——Tab 确认高亮补全项(可下钻项则下钻),Escape 与 Shift+Tab 离开菜单且不选定——其余按键交给编辑器自身。接管键盘的浮层通过 `SessionInput.focus()` 把键盘还回来,该路径走 Lexical 自己的 focus,因此光标回到草稿原来的位置而不是开头。 默认发送采用乐观提交:Enter 在同一事务里清空草稿、occurrence 表和撤销历史,composer 保持 `plain`,发送作为 detached attempt 运行,发送期间可以继续输入和提交。`sendSession` 在序列化之前用投递模式注册 Session 提交回显(`session.beginSubmission`),并在 `pendingSubmissions` 中保留图片与文件的选择顺序;Session 根据该模式与当前运行状态推导位置,因此空闲发送进入 transcript(文本记录),繁忙时 Queue 进入 QueueDock,繁忙时 Steer 进入 pending-steering 区域。随后让出一帧,图片经浏览器原生 `FileReader` data-URL 路径编码,文件则引用已暂存凭证。命令提交也用同一凭证表示通用文件,因此发送 `/goal` 或 `/plan` 时不会再次读取这些浏览器文件。提示词复用提交 `requestId`;queue 或历史以同一 `rpcId` 被观察后,回显只退休一次。多个并发发送失败时,在用户编辑还原内容之前按提交顺序合并还原;命令提交保持冻结的 `submitting` 阶段。Detached attempt 持有附件 id,直到 admission 完成或 Session scope 销毁。回显以 observed 退休时,durable 图片缓存立即公开每个预览 URL,读取 admitted 附件后用规范化 URL 替换预览,并在各 URL 停止使用后撤销,同时释放文件卡。选中的通用文件进入同一个先进先出的后台上传队列;`maxConcurrentFileUploads` 默认允许两个 Worker transport 同时运行,Conversation 服务在切换 Session 时继续持有排队和运行中的传输操作及字节进度,移除草稿会跳过排队中的传输或中止正在运行的传输。continuable 子代理禁用附件入口,也不创建本地回显,因为其 transport 不保留浏览器 request id。 diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx index 2fffc83ecf..460871e0ea 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx @@ -263,7 +263,7 @@ export const InputBar = memo(function InputBar({ // before the launcher opens it: activating the button from the keyboard // leaves focus on the button, and restoring it afterwards would re-track an // empty draft and close the menu again. - editor?.getRootElement()?.focus({ preventScroll: true }) + if (editor !== null) focusDraftEditor(editor, revealSelection) toggleCommandMenu?.(keyboard.caretSpan()) } diff --git a/packages/client/ui-input-trigger/src/client/controller.ts b/packages/client/ui-input-trigger/src/client/controller.ts index 2a5c171931..a297776189 100644 --- a/packages/client/ui-input-trigger/src/client/controller.ts +++ b/packages/client/ui-input-trigger/src/client/controller.ts @@ -130,7 +130,10 @@ export class InputTriggerController { const raw = detectTrigger(draft, caret, guard) if (raw === null) { this.hit = null - this.dismissed = null + // A frozen-tier track is the submit gesture's own bookkeeping, not a new + // intent from the user: a command submitted after a dismissal must not + // re-arm the menu the dismissal closed. + if (guard.tier !== 'frozen') this.dismissed = null this.stopFetch() this.reduce({ type: 'close' }) return diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.tsx b/packages/client/ui-model-selection/src/client/ModelSelect.tsx index df4137a2d8..fb4d985646 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.tsx +++ b/packages/client/ui-model-selection/src/client/ModelSelect.tsx @@ -142,12 +142,15 @@ export function ModelSelect( if (intent === 'drill') { // The checked row is the value in use; a pane without one opens on its // first row. - const checked = menuRef.current?.querySelector('[role="menuitemradio"][aria-checked="true"]') - const target = checked ?? itemRefs.current.find(item => item !== null) - target?.focus() + const checked = menuRef.current?.querySelector('[role="menuitemradio"][aria-checked="true"]:not([disabled])') + const target = checked ?? itemRefs.current.find(item => item !== null && !item.disabled) + // Rows a selection in flight disabled cannot take the keyboard; the + // trigger does, so the card's keys still reach the menu. + ;(target ?? triggerRef.current)?.focus() return } - itemRefs.current[intent === 'effort' ? 1 : 0]?.focus() + const cell = itemRefs.current[intent === 'effort' ? 1 : 0] + ;(cell !== null && cell !== undefined && !cell.disabled ? cell : triggerRef.current)?.focus() }, [open, pane]) // Portaled placement (the Menu primitive's portal rules: fixed from the @@ -242,12 +245,15 @@ export function ModelSelect( return } // Settling activates the row the keyboard is on; with focus still on the - // trigger, Tab enters the menu at the value in use instead. + // trigger, Tab enters the menu at the value in use instead. Any other + // control inside the card (a retry button) keeps the browser's traversal. const focused = document.activeElement - if (focused instanceof HTMLElement && menuRef.current?.contains(focused) === true) { + const rows = itemRefs.current.filter((item): item is HTMLButtonElement => item !== null) + if (focused instanceof HTMLButtonElement && rows.includes(focused)) { focused.click() return } + if (focused !== triggerRef.current) return const checked = menuRef.current?.querySelector('[role="menuitemradio"][aria-checked="true"]') ;(checked ?? itemRefs.current.find(item => item !== null))?.focus() return diff --git a/packages/client/ui-model-selection/tests/model-select.client.spec.tsx b/packages/client/ui-model-selection/tests/model-select.client.spec.tsx index ef6677d4fd..ccd4b2c9d4 100644 --- a/packages/client/ui-model-selection/tests/model-select.client.spec.tsx +++ b/packages/client/ui-model-selection/tests/model-select.client.spec.tsx @@ -315,8 +315,18 @@ describe('ModelSelect keyboard walk', () => { }) it('Tab with the keyboard still on the trigger enters the menu at the value in use', () => { - mountOpen() + render() const trigger = screen.getByRole('button', { name: /选择模型/ }) + // A real click focuses the trigger first; jsdom's does not. + trigger.focus() + fireEvent.click(trigger) expect(fireEvent.keyDown(trigger, { key: 'Tab' })).toBe(false) // The root pane's first cell carries the current selection. const cells = screen.getAllByRole('menuitem') diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 782f420253..b2976071ff 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-primitives/README.md -README.md: cbfda6b0f7a9ac17040c039babfe40db8be3ab42 -README.zh.md: cbe34e697c99e58ea40c6ae4d650883d1aa82e92 +README.md: 5e8b41a3119610ed7ca40f9ca974cc56cfc50cd7 +README.zh.md: 06b56d6dcd629aa1faef36950e6c884a1d863fee diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index cbfda6b0f7..5e8b41a311 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -45,7 +45,7 @@ Check this table before writing a control in a feature package. A plugin cannot | `StateDot` | Status mark: `done`, `warning`, `ongoing`, `error`, or `idle`. `aria-hidden`, so the render site owns the name. | | `ConnectionIndicator` | Inline connection-recovery control across outage, retry, and recovered states. | | `DisclosureRow` | 24px compact disclosure that lays title and content side by side. | -| `Modal` | Centered dialog over a page mask; Escape closes it unless a menu open inside it takes that Escape first. | +| `Modal` | Centered dialog over a page mask. | | `RiskConfirmation` | Sensitive action gated behind an explicit checkbox. | | `OnboardingSurface` | First-run stage that holds the application root inert. | | `Tooltip` | Hover text on a cloned anchor, placed right, bottom, or top. | diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index cbe34e697c..06b56d6dcd 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -45,7 +45,7 @@ kind: "package-library" | `StateDot` | 状态标记:`done`、`warning`、`ongoing`、`error` 或 `idle`。它是 `aria-hidden` 的,名称由渲染点提供。 | | `ConnectionIndicator` | 行内连接恢复控件,覆盖断线、重试与已恢复三种状态。 | | `DisclosureRow` | 24px 紧凑折叠行,标题与内容左右排列。 | -| `Modal` | 页面遮罩之上的居中对话框;Escape 关闭它,除非对话框内有打开的菜单先接管这次 Escape。 | +| `Modal` | 页面遮罩之上的居中对话框。 | | `RiskConfirmation` | 以显式复选框把关的敏感操作确认。 | | `OnboardingSurface` | 首次运行的引导舞台,期间保持应用根节点 inert。 | | `Tooltip` | 克隆锚点上的悬停文本,可置于右、下、上三个方向。 | diff --git a/packages/client/ui-primitives/src/Menu.tsx b/packages/client/ui-primitives/src/Menu.tsx index 51723392af..b78accd8e3 100644 --- a/packages/client/ui-primitives/src/Menu.tsx +++ b/packages/client/ui-primitives/src/Menu.tsx @@ -113,26 +113,44 @@ export function Menu({ open, anchor, items, selectedId, selectedIds, onSelect, o const listRef = useRef(null) /** Index the arrow walk last focused, the resume point when focus left the rows. */ const walkIndex = useRef(null) + /** + * The control that had the keyboard when this menu opened — its own trigger, + * which an anchor that wraps several controls (a split button) would not be + * able to name by position. + */ + const triggerRef = useRef(null) /** - * Hand the keyboard back to the anchor's first button after a close that - * unmounts the rows: focus left on a removed row falls to the page body, - * where the next Tab restarts from the top of the page. + * Hand the keyboard back to the trigger that opened the menu — or, when the + * anchor never held it, to the anchor's first button. Focus left on a removed + * row otherwise falls to the page body, where the next Tab restarts from the + * top of the page. */ const refocusAnchor = (): void => { - rootRef.current?.querySelector('button')?.focus() + const trigger = triggerRef.current + if (trigger !== null && document.contains(trigger) && !(trigger as HTMLButtonElement).disabled) { + trigger.focus() + return + } + rootRef.current?.querySelector('button:not(:disabled)')?.focus() } /** * Post-selection focus, for the paths where the rows unmount with the list. - * An owner that moved focus itself (a card handing it to its preview button) - * keeps its choice: only a keyboard still on the closing list comes back to - * the anchor. + * A selection whose owner keeps the menu open is left alone, and so is an + * owner that moved focus itself (a presented file card hands it to its + * preview button): only a keyboard left on the closing list (or on the body + * its removal produced) comes back to the trigger. */ const refocusAfterSelection = (): void => { - const active = document.activeElement - if (active === null || active === document.body || listRef.current?.contains(active) === true) refocusAnchor() + queueMicrotask(() => { + if (openRef.current) return + const active = document.activeElement + if (active === null || active === document.body || listRef.current?.contains(active) === true) refocusAnchor() + }) } + const openRef = useRef(open) + openRef.current = open const [openSubmenuId, setOpenSubmenuId] = useState(null) const [fixedPos, setFixedPos] = useState(null) const { arm: armClose, cancel: cancelClose } = usePointerGrace(onClose) @@ -190,6 +208,19 @@ export function Menu({ open, anchor, items, selectedId, selectedIds, onSelect, o } }, [open, portal, align, side, getAnchorRect]) + // Opening remembers where the keyboard was, so closing can hand it back to + // that control — an anchor wrapping several (a split button) cannot be asked + // for it by position. Declared before the autoFocus effect so the capture + // sees the trigger, not the row autoFocus is about to focus. + useEffect(() => { + if (!open) { + triggerRef.current = null + return + } + const active = document.activeElement + triggerRef.current = active instanceof HTMLElement && rootRef.current?.contains(active) === true ? active : null + }, [open]) + useEffect(() => { if (!open || !autoFocus) return const first = listRef.current?.querySelector('button:not(:disabled)') @@ -212,12 +243,13 @@ export function Menu({ open, anchor, items, selectedId, selectedIds, onSelect, o } const onKeyDown = (e: KeyboardEvent) => { if (e.key === 'Escape') { - // Closing hands the keyboard back to the anchor whenever the menu had - // it, so Escape leaves the user where it found them. + // Closing hands the keyboard back when the menu had it — and, as this + // primitive always did for autoFocus menus, when it held the keyboard + // and lost it again (a row that unmounted under it). const inMenu = rootRef.current?.contains(document.activeElement) === true || listRef.current?.contains(document.activeElement) === true onClose() - if (inMenu) refocusAnchor() + if (inMenu || autoFocus) refocusAnchor() } // Tab settles like Enter and Shift+Tab leaves like Escape, so a menu's // keys mean what they mean in the composer. Only a keyboard already on @@ -226,21 +258,30 @@ export function Menu({ open, anchor, items, selectedId, selectedIds, onSelect, o if (e.key === 'Tab') { const list = listRef.current const focused = document.activeElement - const anchored = rootRef.current?.contains(focused) === true || list?.contains(focused) === true + const insideList = list?.contains(focused) === true + const anchored = rootRef.current?.contains(focused) === true || insideList if (list === null || !anchored) return - e.preventDefault() if (e.shiftKey) { + e.preventDefault() onClose() refocusAnchor() return } - // Settling the row the keyboard is on; from the trigger, Tab enters the - // list instead (its own foreground meaning). - if (list.contains(focused)) { - (focused as HTMLElement).click() + // Tab settles the row it is on; from anywhere else in the menu region + // it enters the list. A focused control that is not a row (a retry + // button inside an error strip) and a list with no enabled row keep the + // browser's traversal instead of being swallowed. + if (insideList) { + if (focused instanceof Element && focused.getAttribute('role') === 'menuitem') { + e.preventDefault() + ;(focused as HTMLElement).click() + } return } - list.querySelector('button:not(:disabled)')?.focus() + const row = list.querySelector('button:not(:disabled)') + if (row === null) return + e.preventDefault() + row.focus() walkIndex.current = 0 return } diff --git a/packages/client/ui-primitives/src/Modal.tsx b/packages/client/ui-primitives/src/Modal.tsx index 005b69cf9a..574b1f0f35 100644 --- a/packages/client/ui-primitives/src/Modal.tsx +++ b/packages/client/ui-primitives/src/Modal.tsx @@ -42,10 +42,7 @@ export function Modal({ useEffect(() => { if (!open) return const onKeyDown = (e: KeyboardEvent) => { - // An open menu is an inner layer: its own Escape closes it and hands the - // keyboard back to its anchor, so the dialog waits for the next one. - if (e.key !== 'Escape' || document.querySelector('[role="menu"]') !== null) return - onClose() + if (e.key === 'Escape') onClose() } document.addEventListener('keydown', onKeyDown) return () => { document.removeEventListener('keydown', onKeyDown) } diff --git a/packages/client/ui-primitives/tests/atoms.client.spec.tsx b/packages/client/ui-primitives/tests/atoms.client.spec.tsx index 21c2ec4f04..a2f6b70fb9 100644 --- a/packages/client/ui-primitives/tests/atoms.client.spec.tsx +++ b/packages/client/ui-primitives/tests/atoms.client.spec.tsx @@ -1,5 +1,4 @@ // @vitest-environment jsdom -import { useState } from 'react' import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' import { Button, ConnectionIndicator, Input, Menu, Modal, Pill } from '@deepseek-ai/dsh-client-ui-primitives' @@ -257,75 +256,6 @@ describe('Menu', () => { expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: 'Alpha' })) }) - it('leaves Escape to a menu open inside the dialog, then closes on the next one', () => { - const onClose = vi.fn() - const onSelect = vi.fn() - function Host() { - const [menuOpen, setMenuOpen] = useState(false) - return ( - - { setMenuOpen(true) }}>permissions} - items={[{ id: 'a', label: 'Alpha' }]} - onSelect={onSelect} - onClose={() => { setMenuOpen(false) }} - /> - - ) - } - render() - fireEvent.click(screen.getByRole('button', { name: 'permissions' })) - expect(screen.getByRole('menu')).toBeTruthy() - - // The menu is the inner layer: its Escape closes it and keeps the dialog. - fireEvent.keyDown(document, { key: 'Escape' }) - expect(screen.queryByRole('menu')).toBeNull() - expect(onClose).not.toHaveBeenCalled() - expect(screen.getByRole('dialog', { name: 'Settings' })).toBeTruthy() - - // With no menu open, the next Escape reaches the dialog. - fireEvent.keyDown(document, { key: 'Escape' }) - expect(onClose).toHaveBeenCalledTimes(1) - }) - - it('resumes the arrow walk after focus left the rows instead of re-entering', () => { - const rows = [ - { id: 'a', label: 'Alpha' }, - { id: 'b', label: 'Beta' }, - { id: 'c', label: 'Gamma' }, - ] - render( - trigger} items={rows} onSelect={() => {}} onClose={() => {}} />) - const trigger = screen.getByRole('button', { name: 'trigger' }) - const alpha = screen.getByRole('menuitem', { name: 'Alpha' }) - const beta = screen.getByRole('menuitem', { name: 'Beta' }) - trigger.focus() - fireEvent.keyDown(trigger, { key: 'ArrowDown' }) - fireEvent.keyDown(alpha, { key: 'ArrowDown' }) - expect(document.activeElement).toBe(beta) - - // Focus leaves the rows — a portal frame that refused focus, a detached - // node. The next step must resume from Beta, not re-enter at the far end - // (which would alternate between the first and last row forever). - trigger.focus() - fireEvent.keyDown(trigger, { key: 'ArrowUp' }) - expect(document.activeElement).toBe(alpha) - }) - - it('returns the keyboard to the anchor after a row is selected', () => { - const onSelect = vi.fn() - render( - trigger} items={items} onSelect={onSelect} onClose={() => {}} />) - const alpha = screen.getByRole('menuitem', { name: 'Alpha' }) - // autoFocus parked the keyboard on the first row; selecting unmounts the - // rows with the list in the real consumers, so the anchor takes it back. - expect(document.activeElement).toBe(alpha) - fireEvent.click(alpha) - expect(onSelect).toHaveBeenCalledWith('a') - expect(document.activeElement).toBe(screen.getByRole('button', { name: 'trigger' })) - }) - it('renders a non-interactive heading label and a danger row', () => { const onSelect = vi.fn() render( diff --git a/packages/client/ui-settings-general/src/client/SettingsRoot.tsx b/packages/client/ui-settings-general/src/client/SettingsRoot.tsx index 0100531990..33ad30cb1b 100644 --- a/packages/client/ui-settings-general/src/client/SettingsRoot.tsx +++ b/packages/client/ui-settings-general/src/client/SettingsRoot.tsx @@ -57,10 +57,7 @@ function SettingsPanel({ rows, renderSlot, activeId, onSelect, onClose }: PanelP useEffect(() => { const onKeyDown = (e: KeyboardEvent) => { - // A row's open menu is an inner layer: its own Escape closes it, and the - // panel waits for the next one. - if (e.key !== 'Escape' || document.querySelector('[role="menu"]') !== null) return - onClose() + if (e.key === 'Escape') onClose() } document.addEventListener('keydown', onKeyDown) return () => { document.removeEventListener('keydown', onKeyDown) } diff --git a/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx b/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx index 5fc6f0b092..9a83b4274d 100644 --- a/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx +++ b/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx @@ -268,23 +268,6 @@ describe('SettingsPanel close paths', () => { await vi.waitFor(() => { expect(document.activeElement).toBe(trigger) }) }) - it('leaves Escape to a menu open inside the panel, then closes on the next one', async () => { - mount() - const trigger = openPanel() - // The guard's condition is the open menu's marker, which a row's dropdown - // renders inside the panel. - const menu = document.createElement('div') - menu.setAttribute('role', 'menu') - screen.getByRole('dialog').append(menu) - fireEvent.keyDown(document, { key: 'Escape' }) - expect(screen.getByRole('dialog')).toBeTruthy() - - menu.remove() - fireEvent.keyDown(document, { key: 'Escape' }) - expect(screen.queryByRole('dialog')).toBeNull() - await vi.waitFor(() => { expect(document.activeElement).toBe(trigger) }) - }) - it('closes via document-level Escape, restores trigger focus, and unhooks the listener', async () => { mount() const trigger = openPanel() From b263581e920a58f1df8e8570c3f56b650ea336a1 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Tue, 15 Sep 2026 14:21:00 +0800 Subject: [PATCH 08/13] fix(client): answer the review bot's findings on the keyboard hand-offs - The model seat decides before consuming: a focused control that is not a row (a retry button) keeps the browser's traversal, and Tab enters the list only from the trigger. - A launcher-opened menu is a fresh intent, so the dismissal that closed the same token earlier no longer silences it. - Comments and JSDoc now match the implementation: the near-end entry resumes from the walk's last index, Shift+Tab leaves whenever the menu is open, and the anchor hand-back names the control that opened the menu. - The e2e focus assertions all go through `expect.poll`. - Regression coverage for a rowless pane (the trigger keeps the keyboard) and for a focused retry keeping its Tab, in the seat and the popup shell. - The PR records the two public-surface changes (`SessionInput.focus()` in, `bindComposerFocus` out) and the row-fill focus decision. --- ...9-14-composer-selection-keyboard.i18n.yaml | 4 +-- .../2026-09-14-composer-selection-keyboard.md | 2 +- ...26-09-14-composer-selection-keyboard.zh.md | 2 +- apps/web/tests/declared-reasoning.e2e.ts | 10 ++++-- .../tests/popup-view.client.spec.tsx | 12 +++++++ .../src/client/input/editor/keymap.ts | 7 ++-- .../ui-input-trigger/src/client/controller.ts | 3 ++ .../src/client/ModelSelect.tsx | 11 ++++--- .../tests/model-select.client.spec.tsx | 33 +++++++++++++++++++ packages/client/ui-primitives/src/Menu.tsx | 3 +- 10 files changed, 73 insertions(+), 14 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.i18n.yaml b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.i18n.yaml index cc25662ea6..3476259680 100644 --- a/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.md -2026-09-14-composer-selection-keyboard.md: 9d7f8da91bc69b333ab690a32ea74e219961b6e9 -2026-09-14-composer-selection-keyboard.zh.md: c86e42857f66ff5efb0c6a57dce46e3df79cda0c +2026-09-14-composer-selection-keyboard.md: fb353a7072e7c2245aeeb22af9018edd9a6009f0 +2026-09-14-composer-selection-keyboard.zh.md: f51e5ca5096785ae6d059e3c8497292483490437 diff --git a/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.md b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.md index 9d7f8da91b..fb353a7072 100644 --- a/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.md +++ b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.md @@ -20,7 +20,7 @@ The model seat's dropdown (`ModelSelect`, whose Effort row opens the reasoning-l `ModelSelect` keeps `↑`/`↓` as its focus walk over the rows of the shown pane (wrapping; a step taken while the trigger still holds focus enters at the near end). Tab settles: it activates the row the keyboard is on, and with focus still on the trigger it enters the menu at the row of the value in use instead. Escape and Shift+Tab leave a drilled pane first and otherwise close back to the trigger. A pane switch replaces the row that had focus, so each switch names where the keyboard lands: drilling focuses the row of the value in use (its checked row, or the first row when none is marked), and returning to the root pane focuses the cell that opened the pane left. Without that handoff the focus the unmounted row left on the page body sits outside the card's subtree, where its key handling never sees a keystroke. -`Menu`, the shared anchored dropdown behind the composer's permission seat, the preset chip, file cards, and the settings rows, carries the same pairing: while its list is open, Tab settles the focused row — from the anchor's button, Tab enters the list instead — and Escape or Shift+Tab close it and return focus to the anchor's first button. Only a keyboard already on the anchor or inside the list is intercepted, so Tab presses elsewhere on the page keep the browser's traversal even while a menu is open. Selecting a row hands the keyboard back to the anchor unless the owner moved it itself — a card that focuses its own preview keeps it. The arrows, Home, and End walk the list whether or not `autoFocus` is set — that option now decides only whether opening focuses the first row — the row the keyboard is on carries the same fill a hovered row gets, and closing on Escape or Shift+Tab returns focus to the anchor whenever the menu held it. +`Menu`, the shared anchored dropdown behind the composer's permission seat, the preset chip, file cards, and the settings rows, carries the same pairing: while its list is open, Tab settles the focused row — from the anchor's button, Tab enters the list instead — and Escape or Shift+Tab close it and return focus to the anchor's first button. Only a keyboard already on the anchor or inside the list is intercepted, so Tab presses elsewhere on the page keep the browser's traversal even while a menu is open. The row's focus fill is the row's own indication: the browser's default ring would double it, and the fill is the same one the row shows under the pointer, so the visual language stays one per state. Selecting a row hands the keyboard back to the anchor unless the owner moved it itself — a card that focuses its own preview keeps it. The arrows, Home, and End walk the list whether or not `autoFocus` is set — that option now decides only whether opening focuses the first row — the row the keyboard is on carries the same fill a hovered row gets, and closing on Escape or Shift+Tab returns focus to the anchor whenever the menu held it. A dismissed menu stays dismissed: `InputTriggerController` records the identity of the hit the user closed — Escape or Shift+Tab, a pointer dismissal, or a settling pick — and a re-track of that same token with the same query leaves the menu closed, so restoring the caret after a dismissal (or a settled command closing the surface it opened) cannot revive it. A new query or another token re-arms it. diff --git a/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.zh.md b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.zh.md index c86e42857f..f51e5ca509 100644 --- a/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.zh.md +++ b/.agents/notes/implemented/feature/2026-09-14-composer-selection-keyboard.zh.md @@ -20,7 +20,7 @@ composer 内有两个选择界面在打开期间持有焦点,两者都把 Tab `ModelSelect` 的 `↑`/`↓` 仍是在所显示面板行间移动焦点(循环;焦点仍在触发器上时从近端进入)。Tab 执行接受:它激活键盘所在的那一行;焦点仍在触发器上时,改为进入菜单并把焦点放在正在使用的那一行。Escape 与 Shift+Tab 都先退出已下钻的面板,否则关闭并回到触发器。面板切换会替换持有焦点的那一行,因此每次切换都指明键盘的落点:下钻落在正在使用的值那一行(其选中行;没有标记行时为首行),返回根面板则落在打开该面板的那个格子上。没有这一步,已卸载的行留在页面 body 上的焦点就位于卡片自身子树之外,挂在那里的按键处理永远收不到键盘事件。 -`Menu`——权限档位、预设芯片、文件卡与设置行背后的共享锚定下拉——沿用同一组配对:列表打开期间,Tab 选定聚焦行(键盘在锚点按钮上时,Tab 改为进入列表),Escape 或 Shift+Tab 关闭并把焦点还给锚点的第一个按钮。只拦截已经位于锚点或列表内的键盘,因此页面其它位置按下的 Tab 即使在菜单打开时也仍归浏览器。选定一行会把键盘还给锚点——除非拥有者自己移动了焦点(例如文件卡把自己的预览按钮设为焦点)。`↑`/`↓` 与 Home/End 无论是否设置 `autoFocus` 都在列表中走位——该选项如今只决定打开时是否聚焦首行——键盘所在的那一行使用与悬停行相同的填充(否则键盘走位看不出当前行),而 Escape 或 Shift+Tab 关闭时,只要键盘原本在菜单里就把焦点归还锚点。 +`Menu`——权限档位、预设芯片、文件卡与设置行背后的共享锚定下拉——沿用同一组配对:列表打开期间,Tab 选定聚焦行(键盘在锚点按钮上时,Tab 改为进入列表),Escape 或 Shift+Tab 关闭并把焦点还给锚点的第一个按钮。只拦截已经位于锚点或列表内的键盘,因此页面其它位置按下的 Tab 即使在菜单打开时也仍归浏览器。行的焦点填充就是行自己的焦点提示:浏览器默认轮廓会与之叠加,而这一填充与指针悬停时用的是同一个,视觉语言因此一态一义。选定一行会把键盘还给锚点——除非拥有者自己移动了焦点(例如文件卡把自己的预览按钮设为焦点)。`↑`/`↓` 与 Home/End 无论是否设置 `autoFocus` 都在列表中走位——该选项如今只决定打开时是否聚焦首行——键盘所在的那一行使用与悬停行相同的填充(否则键盘走位看不出当前行),而 Escape 或 Shift+Tab 关闭时,只要键盘原本在菜单里就把焦点归还锚点。 被关闭的菜单保持关闭:`InputTriggerController` 记下用户关闭的那个命中(Escape/Shift+Tab、指针关闭或一次落定选定)的身份,同一 token 以同一查询重新 track 时菜单保持关闭,因此关闭后恢复光标、或已选定命令关闭它打开的界面,都无法把它召回来;新的查询或另一个 token 才会重新武装。 diff --git a/apps/web/tests/declared-reasoning.e2e.ts b/apps/web/tests/declared-reasoning.e2e.ts index 087c6753cb..599d98acbf 100644 --- a/apps/web/tests/declared-reasoning.e2e.ts +++ b/apps/web/tests/declared-reasoning.e2e.ts @@ -84,9 +84,15 @@ describe.skipIf(MODE === 'record')('web e2e: declared reasoning efforts reach th { timeout: 10_000 }, ).toBe(true) await page.keyboard.press('ArrowDown') - expect(await levels.nth(1).evaluate(element => element === document.activeElement)).toBe(true) + await expect.poll( + () => levels.nth(1).evaluate(element => element === document.activeElement), + { timeout: 10_000 }, + ).toBe(true) await page.keyboard.press('ArrowDown') - expect(await levels.nth(2).evaluate(element => element === document.activeElement)).toBe(true) + await expect.poll( + () => levels.nth(2).evaluate(element => element === document.activeElement), + { timeout: 10_000 }, + ).toBe(true) // Settling with Tab is the same gesture that saves the default selection, so // the effort lands in the Agent default Settings section beside provider/model. diff --git a/packages/client/ui-commands/tests/popup-view.client.spec.tsx b/packages/client/ui-commands/tests/popup-view.client.spec.tsx index 77b46dfa2e..ee8ffb1fa5 100644 --- a/packages/client/ui-commands/tests/popup-view.client.spec.tsx +++ b/packages/client/ui-commands/tests/popup-view.client.spec.tsx @@ -157,6 +157,18 @@ describe('PopupSelectView', () => { expect(screen.getByText('正在加载选项…')).toBeTruthy() }) + it('Tab stays the browser\'s on a failed load, so the retry stays reachable', async () => { + const popup = new PopupSelectController({ consume: () => true, focusComposer: () => {} }) + render() + await act(async () => { + popup.open('theme', spec({ options: () => Promise.reject(new Error('directory down')) }), 'ctx-A', SEGMENT) + await Promise.resolve() + }) + const search = screen.getByRole('textbox', { name: '筛选选项' }) + expect(fireEvent.keyDown(search, { key: 'Tab' })).toBe(true) + expect(screen.getByRole('button', { name: '重试' })).toBeTruthy() + }) + it('scrolls the highlighted row into view when the highlight moves', async () => { const { search } = await mountOpen() scrollIntoView.mockClear() diff --git a/packages/client/ui-conversation/src/client/input/editor/keymap.ts b/packages/client/ui-conversation/src/client/input/editor/keymap.ts index 671b96713e..42c217caa0 100644 --- a/packages/client/ui-conversation/src/client/input/editor/keymap.ts +++ b/packages/client/ui-conversation/src/client/input/editor/keymap.ts @@ -100,9 +100,10 @@ export function registerComposerKeymap(editor: LexicalEditor, handlers: Composer editor.registerUpdateListener(syncComposition), editor.registerCommand(KEY_ARROW_UP_COMMAND, arrow('up'), COMMAND_PRIORITY_CRITICAL), editor.registerCommand(KEY_ARROW_DOWN_COMMAND, arrow('down'), COMMAND_PRIORITY_CRITICAL), - // Tab settles the highlighted completion; Shift+Tab leaves the menu like - // Escape, so the two Tab gestures never disagree about consuming the draft. - // Without a highlight both pass, keeping native focus traversal. + // Tab settles the highlighted completion and passes without one, keeping + // native focus traversal; Shift+Tab leaves the menu like Escape whenever it + // is open, highlight or not, so the two Tab gestures never disagree about + // consuming the draft. editor.registerCommand( KEY_TAB_COMMAND, event => arrow(event.shiftKey ? 'tabBack' : 'tab')(event), diff --git a/packages/client/ui-input-trigger/src/client/controller.ts b/packages/client/ui-input-trigger/src/client/controller.ts index a297776189..08300d4f20 100644 --- a/packages/client/ui-input-trigger/src/client/controller.ts +++ b/packages/client/ui-input-trigger/src/client/controller.ts @@ -139,6 +139,9 @@ export class InputTriggerController { return } const hit: TriggerHit = { ...raw, span: { ...raw.span, draftRev } } + // A launcher-opened menu is a fresh intent: the dismissal that closed the + // same token earlier must not silence it. + if (launched) this.dismissed = null if (this.dismissed !== null) { if (!dismissedHit(this.dismissed, hit)) this.dismissed = null else { diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.tsx b/packages/client/ui-model-selection/src/client/ModelSelect.tsx index fb4d985646..422994dbb0 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.tsx +++ b/packages/client/ui-model-selection/src/client/ModelSelect.tsx @@ -238,24 +238,27 @@ export function ModelSelect( // keys mean what they mean in the composer. Both are consumed: the card // keeps the browser's focus traversal out while it is open. if (event.key === 'Tab') { - event.preventDefault() if (event.shiftKey) { + event.preventDefault() if (pane !== 'root') back(pane) else close(true) return } // Settling activates the row the keyboard is on; with focus still on the // trigger, Tab enters the menu at the value in use instead. Any other - // control inside the card (a retry button) keeps the browser's traversal. + // control inside the card (a retry button) keeps the browser's traversal, + // so the keystroke stays unconsumed there. const focused = document.activeElement const rows = itemRefs.current.filter((item): item is HTMLButtonElement => item !== null) if (focused instanceof HTMLButtonElement && rows.includes(focused)) { + event.preventDefault() focused.click() return } if (focused !== triggerRef.current) return - const checked = menuRef.current?.querySelector('[role="menuitemradio"][aria-checked="true"]') - ;(checked ?? itemRefs.current.find(item => item !== null))?.focus() + event.preventDefault() + const checked = menuRef.current?.querySelector('[role="menuitemradio"][aria-checked="true"]:not([disabled])') + ;(checked ?? rows.find(item => !item.disabled))?.focus() return } if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { diff --git a/packages/client/ui-model-selection/tests/model-select.client.spec.tsx b/packages/client/ui-model-selection/tests/model-select.client.spec.tsx index ccd4b2c9d4..c2b14e103d 100644 --- a/packages/client/ui-model-selection/tests/model-select.client.spec.tsx +++ b/packages/client/ui-model-selection/tests/model-select.client.spec.tsx @@ -358,6 +358,39 @@ describe('ModelSelect keyboard walk', () => { expect(document.activeElement).toBe(rows[2]) }) + it('keeps the card navigable when a pane has no rows, and leaves a retry its Tab', () => { + const directory = createSnapshotStore(state({ + groups: [], failures: [], status: 'error', error: 'catalog down', + })) + render() + const trigger = screen.getByRole('button', { name: /选择模型/ }) + // A real click focuses the trigger first; jsdom's does not. + trigger.focus() + fireEvent.click(trigger) + fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) + // No rows to hand the keyboard to: the trigger keeps it, so the card's + // keys still reach the menu. + expect(document.activeElement).toBe(trigger) + + const retry = screen.getByRole('button', { name: '重试' }) + retry.focus() + // A control that is not a row keeps the browser's traversal. + expect(fireEvent.keyDown(retry, { key: 'Tab' })).toBe(true) + // Escape still backs out of the pane and then closes the card. + fireEvent.keyDown(retry, { key: 'Escape' }) + // Back on the root pane, whose only cell remains (no model means no effort row). + const cell = screen.getAllByRole('menuitem')[0]! + fireEvent.keyDown(cell, { key: 'Escape' }) + expect(screen.queryByRole('menu')).toBeNull() + }) + it('drills into the model list on the selected model', () => { mountOpen() fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) diff --git a/packages/client/ui-primitives/src/Menu.tsx b/packages/client/ui-primitives/src/Menu.tsx index b78accd8e3..34ca48984a 100644 --- a/packages/client/ui-primitives/src/Menu.tsx +++ b/packages/client/ui-primitives/src/Menu.tsx @@ -287,7 +287,8 @@ export function Menu({ open, anchor, items, selectedId, selectedIds, onSelect, o } // Arrows walk the list whether or not the menu focused its first item on // open, so `autoFocus` chooses only that entry behavior. A keyboard still - // on the anchor enters at the end the step comes from. The walk resumes + // on the anchor enters at the end the step comes from — unless it already + // walked, in which case the walk resumes where it left off. The walk resumes // from where it last put focus, not from `document.activeElement`: a row // that refused focus (a hidden portal frame, a detached node) would // otherwise re-enter at the near end on every press and the walk would From afbe3a4b1d49823b0563b13514faa5e7a737a7b4 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Tue, 15 Sep 2026 14:22:03 +0800 Subject: [PATCH 09/13] refactor(client): compute the menu's keyboard region once per key --- packages/client/ui-primitives/src/Menu.tsx | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/packages/client/ui-primitives/src/Menu.tsx b/packages/client/ui-primitives/src/Menu.tsx index 34ca48984a..bb04912293 100644 --- a/packages/client/ui-primitives/src/Menu.tsx +++ b/packages/client/ui-primitives/src/Menu.tsx @@ -242,14 +242,17 @@ export function Menu({ open, anchor, items, selectedId, selectedIds, onSelect, o onClose() } const onKeyDown = (e: KeyboardEvent) => { + // Where the keyboard is, computed once: the menu owns it when it holds a + // row or sits on its anchor region. + const focused = document.activeElement + const insideList = listRef.current?.contains(focused) === true + const anchored = rootRef.current?.contains(focused) === true || insideList if (e.key === 'Escape') { // Closing hands the keyboard back when the menu had it — and, as this // primitive always did for autoFocus menus, when it held the keyboard // and lost it again (a row that unmounted under it). - const inMenu = rootRef.current?.contains(document.activeElement) === true - || listRef.current?.contains(document.activeElement) === true onClose() - if (inMenu || autoFocus) refocusAnchor() + if (anchored || autoFocus) refocusAnchor() } // Tab settles like Enter and Shift+Tab leaves like Escape, so a menu's // keys mean what they mean in the composer. Only a keyboard already on @@ -257,9 +260,6 @@ export function Menu({ open, anchor, items, selectedId, selectedIds, onSelect, o // page keeps the browser's traversal even while a menu is open. if (e.key === 'Tab') { const list = listRef.current - const focused = document.activeElement - const insideList = list?.contains(focused) === true - const anchored = rootRef.current?.contains(focused) === true || insideList if (list === null || !anchored) return if (e.shiftKey) { e.preventDefault() @@ -295,8 +295,6 @@ export function Menu({ open, anchor, items, selectedId, selectedIds, onSelect, o // alternate between two rows. if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(e.key)) return const list = listRef.current - const focused = document.activeElement - const anchored = rootRef.current?.contains(focused) === true || list?.contains(focused) === true if (list === null || !anchored) return const buttons = Array.from(list.querySelectorAll('button:not(:disabled)')) if (buttons.length === 0) return From 21a785902bf053802525ce21d0726c996b95638a Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Tue, 15 Sep 2026 14:39:21 +0800 Subject: [PATCH 10/13] fix(client): keep a launcher-opened menu open through its own focus track MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Opening the trigger menu from the launcher button has to put the keyboard in the editor for the arrows to drive it, and Lexical's focus restores its selection a tick later — a track the controller read as an empty draft and answered by closing the menu the gesture had just opened. A launcher-opened menu now survives that single follow-up track; typing, picking, Escape or a pointer press still takes over. The access-confirmation golden follows the panel's new highlight: it parks on the row the options mark as the current value rather than the top row. --- .../slash-picker.expected.md | 4 ++-- .../ui-input-trigger/src/client/controller.ts | 6 ++++++ .../tests/service.client.spec.ts | 21 +++++++++++++++++++ 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/apps/web/tests/expected/access-confirmation/slash-picker.expected.md b/apps/web/tests/expected/access-confirmation/slash-picker.expected.md index 488335da2b..ffb1c8bc36 100644 --- a/apps/web/tests/expected/access-confirmation/slash-picker.expected.md +++ b/apps/web/tests/expected/access-confirmation/slash-picker.expected.md @@ -1,8 +1,8 @@ - textbox "筛选选项": - /placeholder: 搜索… - listbox "/permission 匹配项": - - option "仅可查看" [selected] - - option "工作区内修改": + - option "仅可查看" + - option "工作区内修改" [selected]: - text: 工作区内修改 - img - option "完全权限" diff --git a/packages/client/ui-input-trigger/src/client/controller.ts b/packages/client/ui-input-trigger/src/client/controller.ts index 08300d4f20..af5ef3dce0 100644 --- a/packages/client/ui-input-trigger/src/client/controller.ts +++ b/packages/client/ui-input-trigger/src/client/controller.ts @@ -129,6 +129,12 @@ export class InputTriggerController { this.clearLauncher() const raw = detectTrigger(draft, caret, guard) if (raw === null) { + // A launcher-opened menu is opened by a gesture, not by a typed token: + // the focus it takes to drive it with the keyboard re-tracks an empty + // draft right away, and that track must not close what the gesture + // opened. The launcher flag is cleared here, so this holds for that one + // follow-up track only; typing or picking takes over from there. + if (launched) return this.hit = null // A frozen-tier track is the submit gesture's own bookkeeping, not a new // intent from the user: a command submitted after a dismissal must not diff --git a/packages/client/ui-input-trigger/tests/service.client.spec.ts b/packages/client/ui-input-trigger/tests/service.client.spec.ts index 4c9c0bac15..d42a30d65c 100644 --- a/packages/client/ui-input-trigger/tests/service.client.spec.ts +++ b/packages/client/ui-input-trigger/tests/service.client.spec.ts @@ -953,6 +953,27 @@ describe('arbitrate', () => { expect(drillable.picks).toHaveLength(0) }) + it('a launcher-opened menu survives the track its own focus produces', async () => { + const { controller } = await menuBench() + controller.toggleSource('command', { + trigger: '/', query: '', quoted: false, position: 'leading', + span: { start: 0, end: 0, draftRev: 0 }, + }) + expect(controller.menu.getSnapshot().open).toBe(true) + + // Driving the menu with the keyboard focuses the editor, and Lexical's + // deferred selection restore re-tracks an empty draft: the menu stays. + controller.track('', 0, { tier: 'plain' }, 0) + await tick() + expect(controller.menu.getSnapshot().open).toBe(true) + + // Typing takes the ordinary path. + controller.track('/g', 2, { tier: 'plain' }, 1) + await tick() + expect(controller.menu.getSnapshot().open).toBe(true) + expect(controller.launcher.getSnapshot()).toBeNull() + }) + it('a settled pick keeps its menu closed while the same hit re-tracks', async () => { const { controller } = await menuBench() expect(controller.arbitrate('enter', false)).toBe('pick-highlighted') From f2beb99c3bf84021e644cfb5ee3bae2b20593107 Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Wed, 16 Sep 2026 11:26:21 +0800 Subject: [PATCH 11/13] feat(llm): remove the V4 Flash and V4 Flash Vision Exp defaults The shipped DeepSeek catalog keeps V41 Flash and V4 Pro only; the removed ids still pass through as text-only routes when configured explicitly. Updates the adapter tests, the Web settings goldens that render the default catalog, and the regenerated config catalog. --- .../cards.expected.md | 24 ++------------ .../picker.expected.md | 2 -- .../default-models.expected.md | 24 ++------------ .../tests/onboarding-deepseek-config.e2e.ts | 12 +++---- docs/config-catalog.i18n.yaml | 4 +-- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- packages/llm/llm-deepseek/README.i18n.yaml | 4 +-- packages/llm/llm-deepseek/README.md | 4 +-- packages/llm/llm-deepseek/README.zh.md | 4 +-- .../llm/llm-deepseek/src/common/models.ts | 12 ------- packages/llm/llm-deepseek/src/config.ts | 2 +- .../llm/llm-deepseek/tests/adapter.spec.ts | 32 ++++--------------- .../llm-deepseek/tests/dynamic-config.spec.ts | 4 +-- .../tests/messages/adapter.spec.ts | 4 +-- .../tests/messages/serialize.spec.ts | 4 +-- 16 files changed, 32 insertions(+), 108 deletions(-) diff --git a/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md b/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md index 6a74d0a5f3..3f5edb5074 100644 --- a/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md +++ b/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md @@ -49,34 +49,14 @@ - img - textbox "模型 ID 2": - /placeholder: 模型 ID - - text: deepseek-v4-flash + - text: deepseek-v4-pro - textbox "显示名称 2": - /placeholder: 显示名称 - - text: DeepSeek-V4-Flash + - text: DeepSeek-V4-Pro - button "模型选项 2": - img - button "删除模型 2": - img - - textbox "模型 ID 3": - - /placeholder: 模型 ID - - text: deepseek-v4-pro - - textbox "显示名称 3": - - /placeholder: 显示名称 - - text: DeepSeek-V4-Pro - - button "模型选项 3": - - img - - button "删除模型 3": - - img - - textbox "模型 ID 4": - - /placeholder: 模型 ID - - text: deepseek-v4-flash-vision-exp - - textbox "显示名称 4": - - /placeholder: 显示名称 - - text: DeepSeek-V4-Flash-Vision-Exp - - button "模型选项 4": - - img - - button "删除模型 4": - - img - button "添加模型": - img - text: 添加模型 diff --git a/apps/web/tests/expected/deepseek-messages-settings/picker.expected.md b/apps/web/tests/expected/deepseek-messages-settings/picker.expected.md index b61e8f1222..bee6603b9b 100644 --- a/apps/web/tests/expected/deepseek-messages-settings/picker.expected.md +++ b/apps/web/tests/expected/deepseek-messages-settings/picker.expected.md @@ -4,6 +4,4 @@ - menuitemradio "Messages Flash" [checked]: - text: Messages Flash - img - - menuitemradio "DeepSeek-V4-Flash" - menuitemradio "DeepSeek-V4-Pro" - - menuitemradio "DeepSeek-V4-Flash-Vision-Exp" diff --git a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md index 8dadab45e8..750cc087a8 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md @@ -61,34 +61,14 @@ - option "不支持" - textbox "模型 ID 2": - /placeholder: 模型 ID - - text: deepseek-v4-flash + - text: deepseek-v4-pro - textbox "显示名称 2": - /placeholder: 显示名称 - - text: DeepSeek-V4-Flash + - text: DeepSeek-V4-Pro - button "模型选项 2": - img - button "删除模型 2": - img - - textbox "模型 ID 3": - - /placeholder: 模型 ID - - text: deepseek-v4-pro - - textbox "显示名称 3": - - /placeholder: 显示名称 - - text: DeepSeek-V4-Pro - - button "模型选项 3": - - img - - button "删除模型 3": - - img - - textbox "模型 ID 4": - - /placeholder: 模型 ID - - text: deepseek-v4-flash-vision-exp - - textbox "显示名称 4": - - /placeholder: 显示名称 - - text: DeepSeek-V4-Flash-Vision-Exp - - button "模型选项 4": - - img - - button "删除模型 4": - - img - button "添加模型": - img - text: 添加模型 diff --git a/apps/web/tests/onboarding-deepseek-config.e2e.ts b/apps/web/tests/onboarding-deepseek-config.e2e.ts index 8906445d01..b33d29bcb6 100644 --- a/apps/web/tests/onboarding-deepseek-config.e2e.ts +++ b/apps/web/tests/onboarding-deepseek-config.e2e.ts @@ -205,10 +205,8 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup await settings.getByText('自定义设置').click() expect(await settings.getByLabel('模型 ID 1').inputValue()).toBe('deepseek-flash') expect(await settings.getByLabel('显示名称 1').inputValue()).toBe('DeepSeek-V41-Flash') - expect(await settings.getByLabel('模型 ID 2').inputValue()).toBe('deepseek-v4-flash') - expect(await settings.getByLabel('模型 ID 3').inputValue()).toBe('deepseek-v4-pro') - expect(await settings.getByLabel('模型 ID 4').inputValue()).toBe('deepseek-v4-flash-vision-exp') - expect(await settings.getByRole('button', { name: /删除模型/ }).count()).toBe(4) + expect(await settings.getByLabel('模型 ID 2').inputValue()).toBe('deepseek-v4-pro') + expect(await settings.getByRole('button', { name: /删除模型/ }).count()).toBe(2) await settings.getByRole('button', { name: '模型选项 1' }).click() expect(await settings.getByLabel('图片输入 1').inputValue()).toBe('enabled') const defaultModels = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) @@ -225,12 +223,12 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup await expect(scaffold.ctx.llm.resolveModelInfo('deepseek-official', 'deepseek-flash')).resolves.toMatchObject({ name: 'Configured Flash', inputModalities: ['text'], systemPromptUpdate: 'in-history', }) - await expect(scaffold.ctx.llm.resolveModelInfo('deepseek-official', 'deepseek-v4-flash-vision-exp')).resolves.toMatchObject({ - inputModalities: ['text', 'image'], + await expect(scaffold.ctx.llm.resolveModelInfo('deepseek-official', 'deepseek-v4-pro')).resolves.toMatchObject({ + name: 'DeepSeek-V4-Pro', inputModalities: ['text'], }) await deepSeek.locator('xpath=ancestor::li').getByRole('button', { name: '编辑' }).click() await settings.getByText('自定义设置').click() - for (let index = 0; index < 4; index++) { + for (let index = 0; index < 2; index++) { await settings.getByRole('button', { name: /删除模型/ }).first().click() } await settings.getByRole('button', { name: '添加模型' }).click() diff --git a/docs/config-catalog.i18n.yaml b/docs/config-catalog.i18n.yaml index 6d95b62184..dca1dd45b8 100644 --- a/docs/config-catalog.i18n.yaml +++ b/docs/config-catalog.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/config-catalog.md -config-catalog.md: ba691e83e0e81bf608f090c56cca6b797074116b -config-catalog.zh.md: 78d39e6e85329d797699b0a6e9e151e13d48fa5e +config-catalog.md: 57cb0c6b5db3177dfd4a777448cbd726a8e0957c +config-catalog.zh.md: b34da72c2f3496748073171aa0dd3cceefb019bc diff --git a/docs/config-catalog.md b/docs/config-catalog.md index ba691e83e0..57cb0c6b5d 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1150,7 +1150,7 @@ export interface Config { maxTokens?: number /** Positive context capacity used when the selected model has no exact value (default 1,000,000). */ defaultContextWindow?: number - /** Advisory models shown by discovery consumers; defaults to V41 Flash, V4 Flash, V4 Pro, and V4 Flash Vision Exp. */ + /** Advisory models shown by discovery consumers; defaults to V41 Flash and V4 Pro. */ models?: DeepSeekCatalogModel[] /** Maximum provider idle time while one stream read is outstanding (default five minutes). */ streamIdleTimeoutMs?: number diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 78d39e6e85..b34da72c2f 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1152,7 +1152,7 @@ export interface Config { maxTokens?: number /** Positive context capacity used when the selected model has no exact value (default 1,000,000). */ defaultContextWindow?: number - /** Advisory models shown by discovery consumers; defaults to V41 Flash, V4 Flash, V4 Pro, and V4 Flash Vision Exp. */ + /** Advisory models shown by discovery consumers; defaults to V41 Flash and V4 Pro. */ models?: DeepSeekCatalogModel[] /** Maximum provider idle time while one stream read is outstanding (default five minutes). */ streamIdleTimeoutMs?: number diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml index 5acc7950ec..134ca62d40 100644 --- a/packages/llm/llm-deepseek/README.i18n.yaml +++ b/packages/llm/llm-deepseek/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/llm/llm-deepseek/README.md -README.md: 6121a19003a628204bfb5f8a3d6b5d969bd19104 -README.zh.md: 69e5c103e0edd8d16f606ed11a7aaf602ff5944e +README.md: f332d59b0fe63e5129e5205fbba1ab1901b34d7f +README.zh.md: 26ce84e2497c637cbfe42bbbaf72fc07f27c3e82 diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md index 6121a19003..f332d59b0f 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -45,7 +45,7 @@ Choose this adapter for DeepSeek's official API or a gateway that supports the s filesApiTimeoutMs: 60000 ``` -A request selects the route with `provider: deepseek-official`; the model id passes through to the wire, so new DeepSeek models need no re-registration. Omitted `models` advertises the text- and image-capable `deepseek-flash` and `deepseek-v4-flash-vision-exp` alongside the text-only `deepseek-v4-flash` and `deepseek-v4-pro`, each with a 1,000,000-token context window. An explicit list replaces those defaults, and unlisted model ids still pass through as text-only routes. Clients, including model discovery tools, can read the advisory entries through `ctx.llm.listModels('deepseek-official')`. Image-capable entries may set `imagePixelBudget` to a positive integer or `low`, and may set `imageMaxBytes`. An entry may declare `systemPromptUpdate: in-history` when its endpoint reads the latest `system` message at any position of `messages` as the complete effective system prompt; the adapter reports the mode on the resolved model and the prepared call, and the agent loop then appends a changed prompt after the cached history instead of rewriting the leading system message ([decision rule](../../core/agent-loop/README.md#understand-the-implementation)). The default `deepseek-flash` entry declares this mode; other models require an explicit `models` declaration, and any value other than `in-history` fails at load with `llm-deepseek: catalog model "" systemPromptUpdate must be "in-history" when present`. +A request selects the route with `provider: deepseek-official`; the model id passes through to the wire, so new DeepSeek models need no re-registration. Omitted `models` advertises the text- and image-capable `deepseek-flash` alongside the text-only `deepseek-v4-pro`, each with a 1,000,000-token context window. An explicit list replaces those defaults, and unlisted model ids still pass through as text-only routes. Clients, including model discovery tools, can read the advisory entries through `ctx.llm.listModels('deepseek-official')`. Image-capable entries may set `imagePixelBudget` to a positive integer or `low`, and may set `imageMaxBytes`. An entry may declare `systemPromptUpdate: in-history` when its endpoint reads the latest `system` message at any position of `messages` as the complete effective system prompt; the adapter reports the mode on the resolved model and the prepared call, and the agent loop then appends a changed prompt after the cached history instead of rewriting the leading system message ([decision rule](../../core/agent-loop/README.md#understand-the-implementation)). The default `deepseek-flash` entry declares this mode; other models require an explicit `models` declaration, and any value other than `in-history` fails at load with `llm-deepseek: catalog model "" systemPromptUpdate must be "in-history" when present`. | Field | Default | Meaning | |---|---|---| @@ -56,7 +56,7 @@ A request selects the route with `provider: deepseek-official`; the model id pas | `reasoningEffort` | `high` | Default effort: `off`, `low`, `high`, or `max` | | `maxTokens` | `256,000` | Per-request output cap; a model's own cap and explicit request values win | | `defaultContextWindow` | `1,000,000` | Capacity fallback for models without an exact value | -| `models` | V41 Flash + V4 Flash + V4 Pro + V4 Flash Vision Exp | Advisory catalog shown by discovery consumers | +| `models` | V41 Flash + V4 Pro | Advisory catalog shown by discovery consumers | | `streamIdleTimeoutMs` | `300,000` | Maximum provider idle time per outstanding stream read | | `maxRequestFilesBytes` | `128 MiB` | File-mode request-image byte budget; a request whose retained images exceed it fails with `IMAGE_OFFLOAD_REQUIRED` | | `maxInlineRequestImageBytes` | `20 MiB` | Independent base64 fallback high watermark | diff --git a/packages/llm/llm-deepseek/README.zh.md b/packages/llm/llm-deepseek/README.zh.md index 69e5c103e0..26ce84e249 100644 --- a/packages/llm/llm-deepseek/README.zh.md +++ b/packages/llm/llm-deepseek/README.zh.md @@ -45,7 +45,7 @@ kind: "package-reference" filesApiTimeoutMs: 60000 ``` -请求用 `provider: deepseek-official` 选择路由;模型 id 原样传到协议,因此新增 DeepSeek 模型无需重新注册。省略 `models` 时公布支持文本和图像的 `deepseek-flash` 和 `deepseek-v4-flash-vision-exp`,以及仅支持文本的 `deepseek-v4-flash` 和 `deepseek-v4-pro`,各自的上下文窗口均为 1,000,000 token。显式列表会替换这些默认值,未列出的模型 id 仍作为纯文本路由原样通过。包括模型发现工具在内的客户端可通过 `ctx.llm.listModels('deepseek-official')` 读取这些建议性条目。支持图片的条目可把 `imagePixelBudget` 设置为正整数或 `low`,也可以设置 `imageMaxBytes`。当端点把 `messages` 中任意位置最新的 `system` 消息读作完整的有效系统提示词时,条目可以声明 `systemPromptUpdate: in-history`;适配器会在已解析模型与已准备调用上报告该模式,agent loop(智能体循环)随后把变化后的提示词追加到已缓存历史之后,而不是改写开头的 system 消息([决策规则](../../core/agent-loop/README.zh.md#understand-the-implementation))。默认的 `deepseek-flash` 条目声明该模式;其他模型需通过 `models` 显式声明,`in-history` 以外的任何值都会在加载时以 `llm-deepseek: catalog model "" systemPromptUpdate must be "in-history" when present` 失败。 +请求用 `provider: deepseek-official` 选择路由;模型 id 原样传到协议,因此新增 DeepSeek 模型无需重新注册。省略 `models` 时公布支持文本和图像的 `deepseek-flash`,以及仅支持文本的 `deepseek-v4-pro`,各自的上下文窗口均为 1,000,000 token。显式列表会替换这些默认值,未列出的模型 id 仍作为纯文本路由原样通过。包括模型发现工具在内的客户端可通过 `ctx.llm.listModels('deepseek-official')` 读取这些建议性条目。支持图片的条目可把 `imagePixelBudget` 设置为正整数或 `low`,也可以设置 `imageMaxBytes`。当端点把 `messages` 中任意位置最新的 `system` 消息读作完整的有效系统提示词时,条目可以声明 `systemPromptUpdate: in-history`;适配器会在已解析模型与已准备调用上报告该模式,agent loop(智能体循环)随后把变化后的提示词追加到已缓存历史之后,而不是改写开头的 system 消息([决策规则](../../core/agent-loop/README.zh.md#understand-the-implementation))。默认的 `deepseek-flash` 条目声明该模式;其他模型需通过 `models` 显式声明,`in-history` 以外的任何值都会在加载时以 `llm-deepseek: catalog model "" systemPromptUpdate must be "in-history" when present` 失败。 | 字段 | 默认值 | 含义 | |---|---|---| @@ -56,7 +56,7 @@ kind: "package-reference" | `reasoningEffort` | `high` | 默认强度:`off`、`low`、`high` 或 `max` | | `maxTokens` | `256,000` | 单次请求输出上限;模型自身上限与显式请求值优先 | | `defaultContextWindow` | `1,000,000` | 无精确值模型的容量回退 | -| `models` | V41 Flash + V4 Flash + V4 Pro + V4 Flash Vision Exp | 供发现消费方查看的建议性目录 | +| `models` | V41 Flash + V4 Pro | 供发现消费方查看的建议性目录 | | `streamIdleTimeoutMs` | `300,000` | 单次流读取未完成的最大提供方空闲时间 | | `maxRequestFilesBytes` | `128 MiB` | file 模式请求图片字节预算,保留图片超过时请求以 `IMAGE_OFFLOAD_REQUIRED` 失败 | | `maxInlineRequestImageBytes` | `20 MiB` | 独立的 base64 回退高水位 | diff --git a/packages/llm/llm-deepseek/src/common/models.ts b/packages/llm/llm-deepseek/src/common/models.ts index 5eec09b070..8f614db47b 100644 --- a/packages/llm/llm-deepseek/src/common/models.ts +++ b/packages/llm/llm-deepseek/src/common/models.ts @@ -11,22 +11,10 @@ export const DEFAULT_MODELS: DeepSeekCatalogModel[] = [ inputModalities: ['text', 'image'], systemPromptUpdate: 'in-history', }, - { - id: 'deepseek-v4-flash', - name: 'DeepSeek-V4-Flash', - description: 'Fast, efficient, and economical; suited to focused, routine, or parallel tasks.', - contextWindow: DEFAULT_CONTEXT_WINDOW, - }, { id: 'deepseek-v4-pro', name: 'DeepSeek-V4-Pro', description: 'Stronger agentic coding, knowledge, and difficult reasoning; suited to complex or quality-critical tasks at higher cost.', contextWindow: DEFAULT_CONTEXT_WINDOW, }, - { - id: 'deepseek-v4-flash-vision-exp', - name: 'DeepSeek-V4-Flash-Vision-Exp', - contextWindow: DEFAULT_CONTEXT_WINDOW, - inputModalities: ['text', 'image'], - }, ] diff --git a/packages/llm/llm-deepseek/src/config.ts b/packages/llm/llm-deepseek/src/config.ts index 928fe45858..3bf9f5a6d2 100644 --- a/packages/llm/llm-deepseek/src/config.ts +++ b/packages/llm/llm-deepseek/src/config.ts @@ -37,7 +37,7 @@ export interface Config { maxTokens?: number /** Positive context capacity used when the selected model has no exact value (default 1,000,000). */ defaultContextWindow?: number - /** Advisory models shown by discovery consumers; defaults to V41 Flash, V4 Flash, V4 Pro, and V4 Flash Vision Exp. */ + /** Advisory models shown by discovery consumers; defaults to V41 Flash and V4 Pro. */ models?: DeepSeekCatalogModel[] /** Maximum provider idle time while one stream read is outstanding (default five minutes). */ streamIdleTimeoutMs?: number diff --git a/packages/llm/llm-deepseek/tests/adapter.spec.ts b/packages/llm/llm-deepseek/tests/adapter.spec.ts index e43c19c765..690c9fb5b2 100644 --- a/packages/llm/llm-deepseek/tests/adapter.spec.ts +++ b/packages/llm/llm-deepseek/tests/adapter.spec.ts @@ -1712,13 +1712,6 @@ describe('plugin registration and config', () => { expect(ctx.llm.listProviders()).toEqual([{ id: 'deepseek-official', name: 'DeepSeek' }]) await expect(ctx.llm.listModels('deepseek-official')).resolves.toEqual([ { provider: 'deepseek-official', id: 'deepseek-flash', name: 'DeepSeek-V41-Flash', inputModalities: ['text', 'image'] }, - { - provider: 'deepseek-official', - id: 'deepseek-v4-flash', - name: 'DeepSeek-V4-Flash', - description: 'Fast, efficient, and economical; suited to focused, routine, or parallel tasks.', - inputModalities: ['text'], - }, { provider: 'deepseek-official', id: 'deepseek-v4-pro', @@ -1726,7 +1719,6 @@ describe('plugin registration and config', () => { description: 'Stronger agentic coding, knowledge, and difficult reasoning; suited to complex or quality-critical tasks at higher cost.', inputModalities: ['text'], }, - { provider: 'deepseek-official', id: 'deepseek-v4-flash-vision-exp', name: 'DeepSeek-V4-Flash-Vision-Exp', inputModalities: ['text', 'image'] }, ]) await expect(ctx.llm.resolveModelInfo('deepseek-official', 'deepseek-flash')) .resolves.toMatchObject({ @@ -1749,18 +1741,14 @@ describe('plugin registration and config', () => { }) }) - it.each([ - { model: 'deepseek-v4-flash', inputModalities: ['text'] }, - { model: 'deepseek-v4-pro', inputModalities: ['text'] }, - { model: 'deepseek-v4-flash-vision-exp', inputModalities: ['text', 'image'] }, - ])('keeps $model available with its V4 capabilities', async ({ model, inputModalities }) => { + it('keeps deepseek-v4-pro available with its V4 capabilities', async () => { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(LlmDeepSeek, { protocol: 'chat-completions', baseURL: 'http://127.0.0.1:1' }) - const info = await ctx.llm.resolveModelInfo('deepseek-official', model) + const info = await ctx.llm.resolveModelInfo('deepseek-official', 'deepseek-v4-pro') expect(info).toMatchObject({ - id: model, - inputModalities, + id: 'deepseek-v4-pro', + inputModalities: ['text'], context: { contextWindow: 1_000_000 }, defaultMaxTokens: 256_000, }) @@ -1854,13 +1842,6 @@ describe('plugin registration and config', () => { LlmDeepSeek.apply(ctx, { baseURL: 'http://127.0.0.1:1' }) await expect(ctx.llm.listModels('deepseek-official')).resolves.toEqual([ { provider: 'deepseek-official', id: 'deepseek-flash', name: 'DeepSeek-V41-Flash', inputModalities: ['text', 'image'] }, - { - provider: 'deepseek-official', - id: 'deepseek-v4-flash', - name: 'DeepSeek-V4-Flash', - description: 'Fast, efficient, and economical; suited to focused, routine, or parallel tasks.', - inputModalities: ['text'], - }, { provider: 'deepseek-official', id: 'deepseek-v4-pro', @@ -1868,7 +1849,6 @@ describe('plugin registration and config', () => { description: 'Stronger agentic coding, knowledge, and difficult reasoning; suited to complex or quality-critical tasks at higher cost.', inputModalities: ['text'], }, - { provider: 'deepseek-official', id: 'deepseek-v4-flash-vision-exp', name: 'DeepSeek-V4-Flash-Vision-Exp', inputModalities: ['text', 'image'] }, ]) }) @@ -2193,7 +2173,7 @@ describe('plugin registration and config', () => { // First-boot onboarding: the route registers so models stay discoverable; // only the request itself needs a key. expect(ctx.llm.listProviders()).toEqual([{ id: 'deepseek-official', name: 'DeepSeek' }]) - await expect(ctx.llm.listModels('deepseek-official')).resolves.toHaveLength(4) + await expect(ctx.llm.listModels('deepseek-official')).resolves.toHaveLength(2) const first = await assemble(ctx, { model: 'deepseek-v4-flash', messages: [] }) expect(first.finish).toMatchObject({ kind: 'error', failure: { code: 'MISSING_CREDENTIAL' } }) // The guidance leads with the managed credential store. @@ -2281,7 +2261,7 @@ describe('plugin registration and config', () => { expect(adapter).toBeInstanceOf(DeepSeekAdapter) // Direct embedding shares the plugin's one resolve step, so it advertises // the same default catalog instead of a divergent empty one. - await expect(adapter.listModels('deepseek-official')).resolves.toHaveLength(4) + await expect(adapter.listModels('deepseek-official')).resolves.toHaveLength(2) }) it('resolves connection facts and the credential exactly once per stream call', async () => { diff --git a/packages/llm/llm-deepseek/tests/dynamic-config.spec.ts b/packages/llm/llm-deepseek/tests/dynamic-config.spec.ts index 167a675388..505d933a61 100644 --- a/packages/llm/llm-deepseek/tests/dynamic-config.spec.ts +++ b/packages/llm/llm-deepseek/tests/dynamic-config.spec.ts @@ -191,7 +191,7 @@ describe('request-level dynamic configuration', () => { const dir = await home() const { ctx } = await boot(dir, { baseURL: 'http://127.0.0.1:1' }) - await expect(ctx.llm.listModels('deepseek-official')).resolves.toHaveLength(4) + await expect(ctx.llm.listModels('deepseek-official')).resolves.toHaveLength(2) await ctx.settings.update(NS, { models: [{ id: 'settings-model', name: 'From Settings', inputModalities: ['text', 'image'] }], }) @@ -276,7 +276,7 @@ describe('request-level dynamic configuration', () => { // Schema-valid but resolver-invalid: duplicate catalog ids pass the array // schema and fail the explicit resolve step. await ctx.settings.update(NS, { models: [{ id: 'dup' }, { id: 'dup' }] }) - await expect(ctx.llm.listModels('deepseek-official')).resolves.toHaveLength(4) + await expect(ctx.llm.listModels('deepseek-official')).resolves.toHaveLength(2) await ctx.settings.update(NS, { models: [{ id: 'recovered' }] }) await expect(ctx.llm.listModels('deepseek-official')).resolves.toEqual([ { provider: 'deepseek-official', id: 'recovered', name: 'recovered', inputModalities: ['text'] }, diff --git a/packages/llm/llm-deepseek/tests/messages/adapter.spec.ts b/packages/llm/llm-deepseek/tests/messages/adapter.spec.ts index 8eb6d4effe..6af02de01b 100644 --- a/packages/llm/llm-deepseek/tests/messages/adapter.spec.ts +++ b/packages/llm/llm-deepseek/tests/messages/adapter.spec.ts @@ -82,7 +82,7 @@ describe('direct Messages HTTP', () => { }, body: { thinking: { type: 'enabled' }, output_config: { effort: 'high' } } }) expect(llm.providerInfo('deepseek-official')).toEqual({ id: 'deepseek-official', name: 'DeepSeek' }) expect((await llm.listModels('deepseek-official')).map(model => model.id)).toEqual([ - 'deepseek-flash', 'deepseek-v4-flash', 'deepseek-v4-pro', 'deepseek-v4-flash-vision-exp', + 'deepseek-flash', 'deepseek-v4-pro', ]) expect(await llm.resolveModel('deepseek-official', 'deepseek-flash')).toMatchObject({ name: 'DeepSeek-V41-Flash', inputModalities: ['text', 'image'], systemPromptUpdate: 'in-history', @@ -188,7 +188,7 @@ describe('Cordis provider composition', () => { vi.stubEnv('DEEPSEEK_API_KEY', 'test-key') await ctx.plugin(LlmRuntime) await ctx.plugin(Messages, { baseURL: http.url }) - const model = 'deepseek-v4-flash-vision-exp' + const model = 'deepseek-flash' const price = () => ctx.llm.imageRequestPricing('deepseek-official', model)! const dummy = { attachmentId: AttachmentId(`sha256:${'a'.repeat(64)}`), width: 1, height: 1, bytes: 3, mediaType: 'image/png' as const } expect(price().priceImages([{ type: 'image', attachment: dummy }])[0]?.text).toBeDefined() diff --git a/packages/llm/llm-deepseek/tests/messages/serialize.spec.ts b/packages/llm/llm-deepseek/tests/messages/serialize.spec.ts index ada2e7207b..168f912d7b 100644 --- a/packages/llm/llm-deepseek/tests/messages/serialize.spec.ts +++ b/packages/llm/llm-deepseek/tests/messages/serialize.spec.ts @@ -251,11 +251,11 @@ describe('Messages images', () => { const image: ImageBlock = { type: 'image', attachment: ref } const version: RequestImageAttachment = { attachment: ref, variantId: ImageVariantId(`sha256:${'b'.repeat(64)}`), mediaType: 'image/png', bytes: 3, data: Uint8Array.of(1, 2, 3), width: 1, height: 1, depth: 'uchar', space: 'srgb', hasAlpha: false } const access = () => ({ readonlyPath: '/workspace/image.png' }) - const model = 'deepseek-v4-flash-vision-exp' + const model = 'deepseek-flash' // Only the read operation is consumed by image preparation; the transport is mocked, not durable content. const attachments = { readImageRequest: async () => version } as unknown as AttachmentStore const signal = new AbortController().signal - it.each(['deepseek-flash', model])('keeps image bytes inside tool results and deduplicates normalization for %s', async (model) => { + it('keeps image bytes inside tool results and deduplicates normalization', async () => { const history = [assistant([call()]), result('a', [image, image])] const prepared = await prepareImages(history, connection, model, attachments, access, signal) expect(prepared.versions.size).toBe(1) From a55b08233f34ccfdb38943fbeea10feb2cd073b5 Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Wed, 16 Sep 2026 11:39:32 +0800 Subject: [PATCH 12/13] test(llm): point the keyless onboarding case at a listed model The case verifies first-boot catalog browsing and an actionable MISSING_CREDENTIAL, so it follows the default catalog instead of an unlisted id whose route only proves pass-through. --- packages/llm/llm-deepseek/tests/adapter.spec.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/llm/llm-deepseek/tests/adapter.spec.ts b/packages/llm/llm-deepseek/tests/adapter.spec.ts index 690c9fb5b2..767c0d5c73 100644 --- a/packages/llm/llm-deepseek/tests/adapter.spec.ts +++ b/packages/llm/llm-deepseek/tests/adapter.spec.ts @@ -2174,10 +2174,10 @@ describe('plugin registration and config', () => { // only the request itself needs a key. expect(ctx.llm.listProviders()).toEqual([{ id: 'deepseek-official', name: 'DeepSeek' }]) await expect(ctx.llm.listModels('deepseek-official')).resolves.toHaveLength(2) - const first = await assemble(ctx, { model: 'deepseek-v4-flash', messages: [] }) + const first = await assemble(ctx, { model: 'deepseek-flash', messages: [] }) expect(first.finish).toMatchObject({ kind: 'error', failure: { code: 'MISSING_CREDENTIAL' } }) // The guidance leads with the managed credential store. - const second = await assemble(ctx, { model: 'deepseek-v4-flash', messages: [] }) + const second = await assemble(ctx, { model: 'deepseek-flash', messages: [] }) expect(second.finish.kind).toBe('error') if (second.finish.kind !== 'error') throw new Error('expected an error finish') // The guidance names both places a credential can come from, and nothing From a69bcf36369c1f2f4fb18ef7b7a22592de3c76f9 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Wed, 16 Sep 2026 12:51:50 +0800 Subject: [PATCH 13/13] feat(subagent): own editable delegation limits in the backend --- ...-continuable-activation-capacity.i18n.yaml | 4 +- ...6-09-15-continuable-activation-capacity.md | 2 + ...9-15-continuable-activation-capacity.zh.md | 2 + docs/config-catalog.i18n.yaml | 4 +- docs/config-catalog.md | 11 ++-- docs/config-catalog.zh.md | 11 ++-- docs/event-producer-consumer.i18n.yaml | 2 +- docs/event-producer-consumer.md | 8 +-- docs/module-graph.i18n.yaml | 4 +- docs/module-graph.md | 3 +- docs/module-graph.zh.md | 3 +- docs/subsystems/subagent.i18n.yaml | 4 +- docs/subsystems/subagent.md | 7 +++ docs/subsystems/subagent.zh.md | 7 +++ .../extensions/tool-cordis/src/api-catalog.ts | 8 ++- packages/subagent/subagent/README.i18n.yaml | 4 +- packages/subagent/subagent/README.md | 6 ++ packages/subagent/subagent/README.zh.md | 6 ++ packages/subagent/subagent/package.json | 9 ++- .../subagent/src/continuation-activation.ts | 14 ++--- .../subagent/subagent/src/continuation.ts | 2 +- packages/subagent/subagent/src/index.ts | 26 ++++++++- .../subagent/tests/continuation.spec.ts | 57 +++++++++++++++++++ packages/subagent/subagent/tsconfig.json | 3 + .../subagent/tool-subagent/README.i18n.yaml | 4 +- packages/subagent/tool-subagent/README.md | 4 +- packages/subagent/tool-subagent/README.zh.md | 4 +- packages/subagent/tool-subagent/src/index.ts | 13 +++-- .../tests/model-selection-settings.spec.ts | 29 +++++++++- .../tool-subagent/tests/tool-subagent.spec.ts | 12 ++-- .../fixtures/subagent-activation-limit.ts | 3 +- pnpm-lock.yaml | 3 + .../cordis.snapshot.yml | 2 +- .../sdk/subagent-activation-limit/cordis.yml | 2 +- 34 files changed, 223 insertions(+), 60 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-09-15-continuable-activation-capacity.i18n.yaml b/.agents/notes/implemented/feature/2026-09-15-continuable-activation-capacity.i18n.yaml index 2530a6cc64..e1fa88446a 100644 --- a/.agents/notes/implemented/feature/2026-09-15-continuable-activation-capacity.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-09-15-continuable-activation-capacity.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-15-continuable-activation-capacity.md -2026-09-15-continuable-activation-capacity.md: 71cdf421c09c80f232bcd5ef8bdd6f1dc2523edb -2026-09-15-continuable-activation-capacity.zh.md: b55b379352f844297eb529bc32db693fd72642a6 +2026-09-15-continuable-activation-capacity.md: b7361f76bd3fd7f5de745596596b3e5e132c1acb +2026-09-15-continuable-activation-capacity.zh.md: 8d5c306f6c827d761a9e110d8f8c640c83d91a81 diff --git a/.agents/notes/implemented/feature/2026-09-15-continuable-activation-capacity.md b/.agents/notes/implemented/feature/2026-09-15-continuable-activation-capacity.md index 71cdf421c0..b7361f76bd 100644 --- a/.agents/notes/implemented/feature/2026-09-15-continuable-activation-capacity.md +++ b/.agents/notes/implemented/feature/2026-09-15-continuable-activation-capacity.md @@ -16,6 +16,8 @@ The Activation registry reserves a unique slot before fresh or cold-resume recon Pool lookup, admission and release take amortized constant time. A weak root map does not retain dead root Agents; each pool holds only occupied tokens. No Session catalog scan, tree traversal, durable counter, or public capacity-query API is added. +The Host registers the `subagent` settings section over its composition. Each reservation reads the current capacity, so lowering it never evicts resident children or rebuilds their registry. Delegation tools resolve an omitted depth from the same section at each attempt; explicit numeric and provider-managed tool policies retain priority. Keeping counts in the pool and policy in settings avoids a second live counter or a settings-triggered teardown. + ## Alternatives considered A cumulative child count is a separate cost policy and does not release capacity after useful work finishes. Counting model requests would omit waiting parents, queued inbox work, reconstruction and cleanup, all of which retain resources. Scanning resident and pending maps adds work proportional to unrelated live trees. Separate counters require synchronization with slot ownership. diff --git a/.agents/notes/implemented/feature/2026-09-15-continuable-activation-capacity.zh.md b/.agents/notes/implemented/feature/2026-09-15-continuable-activation-capacity.zh.md index b55b379352..8d5c306f6c 100644 --- a/.agents/notes/implemented/feature/2026-09-15-continuable-activation-capacity.zh.md +++ b/.agents/notes/implemented/feature/2026-09-15-continuable-activation-capacity.zh.md @@ -16,6 +16,8 @@ Activation registry 在新建或冷恢复重建首次让出执行前预占唯一 池查找、接纳和释放的摊还时间复杂度均为常数。根代理的弱引用映射不会保留已结束的根 Agent;每个池只持有已占用的 token。不增加 Session 目录扫描、树遍历、持久计数器或公开的容量查询 API。 +Host 在组合配置之上注册 `subagent` 设置分节。每次预占读取当前容量,因此调低上限不会驱逐驻留子代理,也不会重建注册表。委派工具在每次尝试时从同一分节解析省略的深度;显式数值和 provider-managed 工具策略保留优先级。池持有计数、设置持有策略,避免增加第二份在线计数或因设置变更而触发拆除。 + ## Alternatives considered 累计子代理计数是另一种成本策略,不会在有用工作完成后释放容量。只统计模型请求会遗漏等待后代的父代理、收件箱排队内容、重建和清理,这些阶段都占用资源。扫描驻留和待创建映射会增加与无关存活任务树数量成正比的工作。独立计数器需要与名额所有权同步。 diff --git a/docs/config-catalog.i18n.yaml b/docs/config-catalog.i18n.yaml index c5322922f2..986cc71a30 100644 --- a/docs/config-catalog.i18n.yaml +++ b/docs/config-catalog.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/config-catalog.md -config-catalog.md: e93b6df09f865e8800c67faca75e8324e34eca48 -config-catalog.zh.md: ae676b0cc1904727dfbe71c57795bd8d87ff6695 +config-catalog.md: c1632bcaaa173d9b7e06bf282cf2c83c73cb6cb0 +config-catalog.zh.md: d175313d2ba0a71d22e031f63661bac6e8470c3c diff --git a/docs/config-catalog.md b/docs/config-catalog.md index e93b6df09f..c1632bcaaa 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -2578,10 +2578,12 @@ Source: [`packages/storage/storage-sqlite/src/index.ts:24`](../packages/storage/ export interface Config { /** Maximum live continuable children across one root's tree, excluding the root; defaults to 8. */ maxActiveSubagents?: number + /** Default delegation depth for tools without an explicit limit; defaults to 3. */ + maxDepth?: number } ``` -Source: [`packages/subagent/subagent/src/index.ts:189`](../packages/subagent/subagent/src/index.ts) +Source: [`packages/subagent/subagent/src/index.ts:190`](../packages/subagent/subagent/src/index.ts) @@ -3268,13 +3270,14 @@ export interface Config { deny?: string[] } /** - * Maximum child depth: a non-negative safe integer (default `3`; `0` forbids - * delegation entirely), or `'provider-managed'` to send no cap. A numeric cap + * Maximum child depth: a non-negative safe integer (`0` forbids delegation), + * or `'provider-managed'` to send no cap. A numeric cap * requires the provider's `depthLimit` capability (mount fails loud * otherwise). The provider checks the calling agent's current depth at every * start; the tool remains model-visible so runtime policy owns rejection. * `'provider-managed'` is for an out-of-process provider whose recursion - * budget belongs to the child runtime or its own deployment. + * budget belongs to the child runtime or its own deployment. Omission reads + * the current Host subagent depth setting (default `3`) at each delegation. */ maxDepth?: number | 'provider-managed' } diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index ae676b0cc1..d175313d2b 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -2580,10 +2580,12 @@ export type JournalMode = 'wal' | 'delete' | 'truncate' | 'persist' export interface Config { /** Maximum live continuable children across one root's tree, excluding the root; defaults to 8. */ maxActiveSubagents?: number + /** Default delegation depth for tools without an explicit limit; defaults to 3. */ + maxDepth?: number } ``` -来源: [`packages/subagent/subagent/src/index.ts:189`](../packages/subagent/subagent/src/index.ts) +来源: [`packages/subagent/subagent/src/index.ts:190`](../packages/subagent/subagent/src/index.ts) @@ -3270,13 +3272,14 @@ export interface Config { deny?: string[] } /** - * Maximum child depth: a non-negative safe integer (default `3`; `0` forbids - * delegation entirely), or `'provider-managed'` to send no cap. A numeric cap + * Maximum child depth: a non-negative safe integer (`0` forbids delegation), + * or `'provider-managed'` to send no cap. A numeric cap * requires the provider's `depthLimit` capability (mount fails loud * otherwise). The provider checks the calling agent's current depth at every * start; the tool remains model-visible so runtime policy owns rejection. * `'provider-managed'` is for an out-of-process provider whose recursion - * budget belongs to the child runtime or its own deployment. + * budget belongs to the child runtime or its own deployment. Omission reads + * the current Host subagent depth setting (default `3`) at each delegation. */ maxDepth?: number | 'provider-managed' } diff --git a/docs/event-producer-consumer.i18n.yaml b/docs/event-producer-consumer.i18n.yaml index 060150d5cc..5c86bdc3e9 100644 --- a/docs/event-producer-consumer.i18n.yaml +++ b/docs/event-producer-consumer.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/event-producer-consumer.md -event-producer-consumer.md: ad9d4e00cb7b86ad2a080b7b602e035d4854b343 +event-producer-consumer.md: 2cfd3c3bcde3d016e9e1c4244d9a48d0aec988d1 event-producer-consumer.zh.md: 69ca8071bd4574fee9a50799b25c5771cf6644e8 diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index ad9d4e00cb..2cfd3c3bcd 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -61,10 +61,10 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:105`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`events.dispatch`) | `remotes` | | `settings/updated` | `emit` | [`packages/settings/settings/src/types.ts:92`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`events.dispatch`) | [`settings`](../packages/settings/settings) | | `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:296`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - | -| `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:171`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/hooks/hooks-claude-code), `server`, [`subagent`](../packages/subagent/subagent) | -| `subagent/provider-added` | `emit` | [`packages/subagent/subagent/src/index.ts:145`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`emit`) | [`subagent`](../packages/subagent/subagent), [`tool-subagent`](../packages/subagent/tool-subagent) | -| `subagent/provider-removed` | `emit` | [`packages/subagent/subagent/src/index.ts:151`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`subagent`](../packages/subagent/subagent), [`tool-subagent`](../packages/subagent/tool-subagent) | -| `subagent/start` | `emit` | [`packages/subagent/subagent/src/index.ts:162`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`subagent`](../packages/subagent/subagent) | +| `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:172`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/hooks/hooks-claude-code), `server`, [`subagent`](../packages/subagent/subagent) | +| `subagent/provider-added` | `emit` | [`packages/subagent/subagent/src/index.ts:146`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`emit`) | [`subagent`](../packages/subagent/subagent), [`tool-subagent`](../packages/subagent/tool-subagent) | +| `subagent/provider-removed` | `emit` | [`packages/subagent/subagent/src/index.ts:152`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`subagent`](../packages/subagent/subagent), [`tool-subagent`](../packages/subagent/tool-subagent) | +| `subagent/start` | `emit` | [`packages/subagent/subagent/src/index.ts:163`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`subagent`](../packages/subagent/subagent) | | `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:31`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | [`agent`](../packages/core/agent), [`agent-presets`](../packages/preset/agent-presets), `browser-use-runtime`, [`session-reference`](../packages/context/session-reference), [`system-prompt`](../packages/core/system-prompt) | | `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:37`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | | `tools/change` | `emit` | [`packages/core/tools/src/index.ts:201`](../packages/core/tools/src/index.ts) | [`agent-presets`](../packages/preset/agent-presets) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime`, [`tool-subagent`](../packages/subagent/tool-subagent) | diff --git a/docs/module-graph.i18n.yaml b/docs/module-graph.i18n.yaml index 21ea52cffa..58302f9f6c 100644 --- a/docs/module-graph.i18n.yaml +++ b/docs/module-graph.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/module-graph.md -module-graph.md: 719273c14784fcf5dd98b2fddabfb7666c666139 -module-graph.zh.md: b1098cc39fdc1d44f9d7edc3555d18a2f2c26bc5 +module-graph.md: 2b8f34025fc87eb3611cb7902597afe03ad761aa +module-graph.zh.md: f8f8f1693a11e9fce21a309205a7dbd445a3fc9b diff --git a/docs/module-graph.md b/docs/module-graph.md index 719273c147..2b8f34025f 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -1062,6 +1062,7 @@ flowchart TD pkg_subagent --> pkg_session_projection pkg_subagent --> pkg_session_projection_cache pkg_subagent --> pkg_session_query + pkg_subagent --> pkg_settings pkg_subagent --> pkg_system_prompt pkg_subagent --> pkg_tools pkg_subagent --> pkg_typert_protocol @@ -1542,7 +1543,7 @@ flowchart TD | [`subprocess-ssh`](../packages/ssh/subprocess-ssh) | `ssh` | [`ssh`](../packages/ssh/ssh), [`subprocess`](../packages/subprocess/subprocess), [`subprocess-local`](../packages/subprocess/subprocess-local) | | [`agent-loop-testkit`](../packages/test-support/agent-loop-testkit) | `test-support` | [`agent`](../packages/core/agent), [`agent-loop`](../packages/core/agent-loop), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`webhook`](../packages/webhook/webhook) | `webhook` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-presets`](../packages/preset/agent-presets), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) | -| [`subagent`](../packages/subagent/subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-presets`](../packages/preset/agent-presets), [`attachment`](../packages/attachment/attachment), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval), [`util-time`](../packages/util/time) | +| [`subagent`](../packages/subagent/subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-presets`](../packages/preset/agent-presets), [`attachment`](../packages/attachment/attachment), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`settings`](../packages/settings/settings), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval), [`util-time`](../packages/util/time) | | [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query) | | [`tool-session-query`](../packages/session-query/tool-session-query) | `session-query` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`mcp-client`](../packages/mcp/mcp-client), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`token-meter`](../packages/llm/token-meter), [`user-approval`](../packages/interaction/user-approval) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index b1098cc39f..f8f8f1693a 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -1064,6 +1064,7 @@ flowchart TD pkg_subagent --> pkg_session_projection pkg_subagent --> pkg_session_projection_cache pkg_subagent --> pkg_session_query + pkg_subagent --> pkg_settings pkg_subagent --> pkg_system_prompt pkg_subagent --> pkg_tools pkg_subagent --> pkg_typert_protocol @@ -1544,7 +1545,7 @@ flowchart TD | [`subprocess-ssh`](../packages/ssh/subprocess-ssh) | `ssh` | [`ssh`](../packages/ssh/ssh), [`subprocess`](../packages/subprocess/subprocess), [`subprocess-local`](../packages/subprocess/subprocess-local) | | [`agent-loop-testkit`](../packages/test-support/agent-loop-testkit) | `test-support` | [`agent`](../packages/core/agent), [`agent-loop`](../packages/core/agent-loop), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`webhook`](../packages/webhook/webhook) | `webhook` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-presets`](../packages/preset/agent-presets), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) | -| [`subagent`](../packages/subagent/subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-presets`](../packages/preset/agent-presets), [`attachment`](../packages/attachment/attachment), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval), [`util-time`](../packages/util/time) | +| [`subagent`](../packages/subagent/subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-presets`](../packages/preset/agent-presets), [`attachment`](../packages/attachment/attachment), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`settings`](../packages/settings/settings), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval), [`util-time`](../packages/util/time) | | [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query) | | [`tool-session-query`](../packages/session-query/tool-session-query) | `session-query` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`mcp-client`](../packages/mcp/mcp-client), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`token-meter`](../packages/llm/token-meter), [`user-approval`](../packages/interaction/user-approval) | diff --git a/docs/subsystems/subagent.i18n.yaml b/docs/subsystems/subagent.i18n.yaml index f9b7d9ae89..40eb23bda8 100644 --- a/docs/subsystems/subagent.i18n.yaml +++ b/docs/subsystems/subagent.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/subagent.md -subagent.md: 21c75626158db666fd72bed2742b30e12f4cb719 -subagent.zh.md: ca4bb724b82f4f9e81f1e5b7653950ad8c2d3745 +subagent.md: 74d08b108c8a248873228e6e4c940db90b937b9b +subagent.zh.md: e7cefff85ac79cb9411ac301e09793336cdb9c2b diff --git a/docs/subsystems/subagent.md b/docs/subsystems/subagent.md index 21c7562615..74d08b108c 100644 --- a/docs/subsystems/subagent.md +++ b/docs/subsystems/subagent.md @@ -494,6 +494,13 @@ Source: [`packages/subagent/tool-subagent/src/model-selection-settings.ts`](../. Named provider registry with one-shot runs, durable discovery, and continuable-child operations. ```ts cordis-catalog +/** + * Resolve a delegation tool's depth policy against the current user setting. + * @param configured - Explicit tool limit, or provider-managed for external delegation. + * @returns The numeric limit, or undefined when the provider owns depth enforcement. + */ +resolveMaxDepth(configured?: number | 'provider-managed'): number | undefined + /** * Establish one durable continuable child and deliver its initial prompt. * Resolves when the child's inbox accepts that prompt, without waiting for the diff --git a/docs/subsystems/subagent.zh.md b/docs/subsystems/subagent.zh.md index ca4bb724b8..e7cefff85a 100644 --- a/docs/subsystems/subagent.zh.md +++ b/docs/subsystems/subagent.zh.md @@ -498,6 +498,13 @@ Source: [`packages/subagent/tool-subagent/src/model-selection-settings.ts`](../. Named provider registry with one-shot runs, durable discovery, and continuable-child operations. ```ts cordis-catalog +/** + * Resolve a delegation tool's depth policy against the current user setting. + * @param configured - Explicit tool limit, or provider-managed for external delegation. + * @returns The numeric limit, or undefined when the provider owns depth enforcement. + */ +resolveMaxDepth(configured?: number | 'provider-managed'): number | undefined + /** * Establish one durable continuable child and deliver its initial prompt. * Resolves when the child's inbox accepts that prompt, without waiting for the diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 515cc0f70d..a96f4fcaa5 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -2460,6 +2460,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ summary: 'Named provider registry with one-shot runs, durable discovery, and continuable-child operations.', description: 'Named provider registry with one-shot runs, durable discovery, and continuable-child operations.', methods: [ + { + signature: 'resolveMaxDepth(configured?: number | \'provider-managed\'): number | undefined', + description: 'Resolve a delegation tool\'s depth policy against the current user setting.', + parameters: [{ name: 'configured', description: 'Explicit tool limit, or provider-managed for external delegation.' }], + returns: 'The numeric limit, or undefined when the provider owns depth enforcement.', + }, { signature: 'async startContinuable(spec: ContinuableStartSpec): Promise', description: 'Establish one durable continuable child and deliver its initial prompt. Resolves when the child\'s inbox accepts that prompt, without waiting for the turn to start or for the message to reach the Session log; any earlier failure rejects with no ids and rolls back the child entirely.', @@ -6203,7 +6209,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SubagentRuntime', - declaration: 'export class SubagentRuntime extends TypertRemoteService {\n static Config: z;\n constructor(ctx: Context, config: Config);\n async startContinuable(spec: ContinuableStartSpec): Promise;\n async sendMessage(sender: Agent, targetId: SessionId, content: ContentBlock[], options: SubagentSendMessageOptions): Promise;\n interrupt(targetSessionId: SessionId, authority: SubagentInterruptAuthority): void;\n async drainContinuableDescendants(parents: readonly Agent[]): Promise;\n async drainContinuableChildren(parent: Agent, childIds: readonly SessionId[]): Promise;\n listChildren(parentSessionId: SessionId, signal?: AbortSignal): Promise;\n listDescendants(rootSessionId: SessionId, signal?: AbortSignal): Promise;\n @Remote(\'list\')\n async remoteExportList(parentSessionId: SessionId, signal: AbortSignal): Promise;\n @Remote(\'prompt\')\n async prompt(request: SubagentPromptRequest, signal: AbortSignal): Promise;\n @Remote(\'interruptByParent\')\n interruptByParent(childSessionId: SessionId, parentSessionId: SessionId, mode: \'continuable\'): SubagentInterruptReceipt;\n registerProvider(provider: SubagentProvider): () => void;\n getProvider(name: string): SubagentProvider | undefined;\n list(): string[];\n async start(name: string, request: SubagentStartRequest): Promise;\n}', + declaration: 'export class SubagentRuntime extends TypertRemoteService {\n static Config: z;\n constructor(ctx: Context, config: Config);\n resolveMaxDepth(configured?: number | \'provider-managed\'): number | undefined;\n async startContinuable(spec: ContinuableStartSpec): Promise;\n async sendMessage(sender: Agent, targetId: SessionId, content: ContentBlock[], options: SubagentSendMessageOptions): Promise;\n interrupt(targetSessionId: SessionId, authority: SubagentInterruptAuthority): void;\n async drainContinuableDescendants(parents: readonly Agent[]): Promise;\n async drainContinuableChildren(parent: Agent, childIds: readonly SessionId[]): Promise;\n listChildren(parentSessionId: SessionId, signal?: AbortSignal): Promise;\n listDescendants(rootSessionId: SessionId, signal?: AbortSignal): Promise;\n @Remote(\'list\')\n async remoteExportList(parentSessionId: SessionId, signal: AbortSignal): Promise;\n @Remote(\'prompt\')\n async prompt(request: SubagentPromptRequest, signal: AbortSignal): Promise;\n @Remote(\'interruptByParent\')\n interruptByParent(childSessionId: SessionId, parentSessionId: SessionId, mode: \'continuable\'): SubagentInterruptReceipt;\n registerProvider(provider: SubagentProvider): () => void;\n getProvider(name: string): SubagentProvider | undefined;\n list(): string[];\n async start(name: string, re /* …truncated — full shape in source */', }, { name: 'SubagentSendMessageOptions', diff --git a/packages/subagent/subagent/README.i18n.yaml b/packages/subagent/subagent/README.i18n.yaml index 06f2eeb0b0..9cedb7e531 100644 --- a/packages/subagent/subagent/README.i18n.yaml +++ b/packages/subagent/subagent/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/subagent/README.md -README.md: ea542aba2fa482618d75342941043a4f3b6bd531 -README.zh.md: 57efd34abbc022b5ab3429c7a951bc679d3c1c69 +README.md: a38022d7f6373a7cf40b42cf944449eabc5aef90 +README.zh.md: 452b4648a018f788daf1d881c8ed3e91b77286e7 diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index ea542aba2f..a38022d7f6 100644 --- a/packages/subagent/subagent/README.md +++ b/packages/subagent/subagent/README.md @@ -42,10 +42,16 @@ Mount the service with a provider and the delegation tool. The provider register An agent that calls the tool gets the child's final answer as the tool result. Mounting the service alone changes nothing: nothing can delegate until a provider and a tool are composed. +### Delegation settings + +The Host exposes delegation defaults in the `subagent` settings section. User values override this plugin's composition; reset removes the user override. `maxDepth` defaults to `3` and supplies the delegation tools' depth when their own configuration omits it. An explicit tool depth, including `provider-managed`, takes precedence. Depth `0` disables delegation through tools inheriting this setting; depth `1` permits direct children only. Changes apply on the next delegation attempt. Direct service callers continue to supply their own optional request depth. + ### Continuable capacity Set `maxActiveSubagents` on the host `dsh-subagent` plugin to limit live continuable children across each root Agent's entire continuable tree. It defaults to `8` and accepts positive safe integers. The root does not consume a slot; descendants inherit one shared pool. Fresh creation and cold resume reserve before reconstructing the Agent, and cleanup returns the slot after handle disposal. A waiting parent, pending inbox work, and an Activation being stopped still occupy slots. Messages to a resident child reuse its slot. One-shot and external-provider runs are outside this limit; depth remains the delegation tool's separate policy. +The current `maxActiveSubagents` value is sampled before every new or cold-resumed Activation. Raising it admits more children in existing trees; lowering it leaves resident children running and refuses further admissions until usage is below the limit. + At capacity, creation or cold resume rejects with `ACTIVATION_LIMIT_REACHED`: wait for a child to finish or continue using the existing agents. Admission does not queue, because a parent waiting for descendants must not wait for its own occupied slot. Slots are process-local and do not constrain cumulative Session history or token usage. ### One-shot and continuable children diff --git a/packages/subagent/subagent/README.zh.md b/packages/subagent/subagent/README.zh.md index 57efd34abb..452b4648a0 100644 --- a/packages/subagent/subagent/README.zh.md +++ b/packages/subagent/subagent/README.zh.md @@ -42,10 +42,16 @@ kind: "package-reference" 调用该工具的 agent 会把子 agent 的最终答案作为工具结果收到。只挂载服务本身不会改变任何行为:在组合出提供方和工具之前,什么都不能委派。 +### 委派设置 + +Host 在 `subagent` 设置分节中提供委派默认值。用户值覆盖本插件的组合配置;恢复默认会删除用户覆盖。`maxDepth` 默认为 `3`,在委派工具自身未配置深度时提供默认值。工具显式指定的深度(包括 `provider-managed`)优先。深度 `0` 禁止继承此设置的工具委派;深度 `1` 只允许直接子代理。修改在下一次委派时生效。直接调用服务的调用方仍自行提供可选的请求深度。 + ### 可续接子代理容量 在 Host 的 `dsh-subagent` 插件上设置 `maxActiveSubagents`,限制每个根 Agent 的整棵可续接子代理树中存活的子代理数。默认值为 `8`,接受正安全整数。根 Agent 不占名额;后代继承同一个共享池。新建和冷恢复在重建 Agent 前预占名额,清理在 handle 释放后归还名额。等待后代的父代理、有待处理收件箱内容的代理以及正在停止的 Activation 仍占名额。向驻留子代理发送消息复用其名额。一次性和外部提供方运行不受此限制;深度仍由委派工具的独立策略决定。 +每次新建或冷恢复 Activation 前都会读取当前 `maxActiveSubagents`。调高后已有树可接纳更多子代理;调低后驻留子代理继续运行,使用量降至上限以下前拒绝新接纳。 + 容量耗尽时,新建或冷恢复以 `ACTIVATION_LIMIT_REACHED` 拒绝:等待子代理完成,或继续使用现有代理。接纳不会排队,避免等待后代的父代理又等待自己占用的名额。名额仅存在于当前进程,不限制累计 Session 历史或 token 用量。 ### 一次性与可继续子级 diff --git a/packages/subagent/subagent/package.json b/packages/subagent/subagent/package.json index 4d3b6205f4..16394a723a 100644 --- a/packages/subagent/subagent/package.json +++ b/packages/subagent/subagent/package.json @@ -80,7 +80,8 @@ "@deepseek-ai/dsh-typert-protocol": "workspace:^", "@deepseek-ai/dsh-user-approval": "workspace:^", "@deepseek-ai/dsh-util-time": "workspace:^", - "@deepseek-ai/dsh-permission-presets": "workspace:^" + "@deepseek-ai/dsh-permission-presets": "workspace:^", + "@deepseek-ai/dsh-settings": "workspace:^" }, "peerDependenciesMeta": { "@deepseek-ai/dsh-agent-presets": { @@ -112,6 +113,9 @@ }, "@deepseek-ai/dsh-user-approval": { "optional": true + }, + "@deepseek-ai/dsh-settings": { + "optional": true } }, "devDependencies": { @@ -139,6 +143,7 @@ "@deepseek-ai/dsh-typert-protocol": "workspace:^", "@deepseek-ai/dsh-user-approval": "workspace:^", "@deepseek-ai/dsh-util-time": "workspace:^", - "@deepseek-ai/dsh-permission-presets": "workspace:^" + "@deepseek-ai/dsh-permission-presets": "workspace:^", + "@deepseek-ai/dsh-settings": "workspace:^" } } diff --git a/packages/subagent/subagent/src/continuation-activation.ts b/packages/subagent/subagent/src/continuation-activation.ts index 975ac87a90..7ff3ef8e78 100644 --- a/packages/subagent/subagent/src/continuation-activation.ts +++ b/packages/subagent/subagent/src/continuation-activation.ts @@ -41,13 +41,11 @@ import type { ActivationObserver, ActivationTerminal } from './lifecycle.ts' class ActivationPool { private readonly slots = new Set() - constructor(private readonly capacity: number) {} - /** Reserve before reconstruction; the returned release also tolerates unpublished rollback. */ - reserve(): () => void { - if (this.slots.size >= this.capacity) { + reserve(capacity: number): () => void { + if (this.slots.size >= capacity) { throw new SubagentError( - `subagent limit reached (${this.capacity} active children); wait for an existing child to finish ` + `subagent limit reached (${capacity} active children); wait for an existing child to finish ` + 'or complete this work with the current agents', 'ACTIVATION_LIMIT_REACHED', ) @@ -207,7 +205,7 @@ export class ContinuableActivationRegistry { childId: SessionId, parent: Agent, ) => ActivationObserver, - private readonly maxActiveSubagents: number, + private readonly maxActiveSubagents: () => number, ) { // Ordinary Cordis owner effects unwind in reverse registration order, which // cannot express the dynamic child graph. Register the private scope's @@ -488,7 +486,7 @@ export class ContinuableActivationRegistry { inputs.signal.throwIfAborted() const lineage = this.liveLineage(inputs.parent) const pool = this.resident.get(inputs.parent.id)?.pool ?? this.rootPool(inputs.parent) - const releaseSlot = pool.reserve() + const releaseSlot = pool.reserve(this.maxActiveSubagents()) const settled = Promise.withResolvers() const materialization: Materialization = { lineage, @@ -607,7 +605,7 @@ export class ContinuableActivationRegistry { private rootPool(parent: Agent): ActivationPool { let pool = this.rootPools.get(parent) if (pool === undefined) { - pool = new ActivationPool(this.maxActiveSubagents) + pool = new ActivationPool() this.rootPools.set(parent, pool) } return pool diff --git a/packages/subagent/subagent/src/continuation.ts b/packages/subagent/subagent/src/continuation.ts index ba6d3b4601..87fae7096a 100644 --- a/packages/subagent/subagent/src/continuation.ts +++ b/packages/subagent/subagent/src/continuation.ts @@ -85,7 +85,7 @@ export class SubagentContinuationManager { constructor( private readonly ctx: Context, private readonly host: ContinuationHost, - maxActiveSubagents: number, + maxActiveSubagents: () => number, ) { this.activations = new ContinuableActivationRegistry( ctx, diff --git a/packages/subagent/subagent/src/index.ts b/packages/subagent/subagent/src/index.ts index 2e07055648..0fa3d5b5a7 100644 --- a/packages/subagent/subagent/src/index.ts +++ b/packages/subagent/subagent/src/index.ts @@ -31,6 +31,7 @@ import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' +import type {} from '@deepseek-ai/dsh-settings' import type {} from '@deepseek-ai/dsh-attachment' import { scopeTarget } from '@deepseek-ai/dsh-scope' import type { Scoped } from '@deepseek-ai/dsh-scope' @@ -189,13 +190,17 @@ interface BrowserPromptSource { export interface Config { /** Maximum live continuable children across one root's tree, excluding the root; defaults to 8. */ maxActiveSubagents?: number + /** Default delegation depth for tools without an explicit limit; defaults to 3. */ + maxDepth?: number } /** Named provider registry with one-shot runs, durable discovery, and continuable-child operations. */ export class SubagentRuntime extends TypertRemoteService { static Config: z = z.object({ + maxDepth: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(3), maxActiveSubagents: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(8), }) + private settingsSource: () => Config private providers = new Map() private continuations: SubagentContinuationManager | undefined /** @@ -207,12 +212,21 @@ export class SubagentRuntime extends TypertRemoteService { constructor(ctx: Context, config: Config) { super(ctx, 'subagents') + assertSubagentMaxDepth(config.maxDepth) + this.settingsSource = () => config + ctx.inject(['settings'], (settingsCtx) => { + settingsCtx.settings.installSection(ctx, 'subagent', SubagentRuntime.Config, config, { + validate: (value) => { assertSubagentMaxDepth(value.maxDepth) }, + setSource: (source) => { this.settingsSource = source }, + onChange: () => {}, + }) + }) this.emitLifecycle = createLifecycleEmitter(this.ctx, parent => scopeTarget(this, parent)) ctx.inject(['agents'], (childCtx: Context) => { const manager = new SubagentContinuationManager(childCtx, { prepareContinuable: (name, request) => this.prepareContinuable(name, request), observeActivation: (provider, childId, parent) => this.observeActivation(provider, childId, parent), - }, (config as Required).maxActiveSubagents) + }, () => (this.settingsSource() as Required).maxActiveSubagents) this.continuations = manager childCtx.effect(() => () => { /* v8 ignore else -- one injected binding owns the slot until its fiber disposes. */ @@ -226,6 +240,16 @@ export class SubagentRuntime extends TypertRemoteService { }) } + /** + * Resolve a delegation tool's depth policy against the current user setting. + * @param configured - Explicit tool limit, or provider-managed for external delegation. + * @returns The numeric limit, or undefined when the provider owns depth enforcement. + */ + resolveMaxDepth(configured?: number | 'provider-managed'): number | undefined { + if (configured === 'provider-managed') return undefined + return configured ?? (this.settingsSource() as Required).maxDepth + } + /** * Establish one durable continuable child and deliver its initial prompt. * Resolves when the child's inbox accepts that prompt, without waiting for the diff --git a/packages/subagent/subagent/tests/continuation.spec.ts b/packages/subagent/subagent/tests/continuation.spec.ts index a883f81ca7..7f37523cd7 100644 --- a/packages/subagent/subagent/tests/continuation.spec.ts +++ b/packages/subagent/subagent/tests/continuation.spec.ts @@ -3,6 +3,7 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' +import { SettingsProvider, type SettingsNamespace } from '@deepseek-ai/dsh-settings' import type { Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' @@ -32,6 +33,13 @@ import { dropContinuationActivation, } from './continuation-internals.ts' +/** Writable settings isolated to one test Context. */ +class MemorySettings extends SettingsProvider { + get writable(): boolean { return true } + protected load(): Promise> { return Promise.resolve({}) } + protected persist(_ns: SettingsNamespace, _section: Record): Promise { return Promise.resolve() } +} + type Script = ConstructorParameters[0] /** One scripted response that may wait on a caller-released gate before streaming. */ @@ -261,6 +269,55 @@ describe('continuable activation capacity', () => { } }) + it('layers editable depth over composition and removes the section on disposal', async () => { + const ctx = new Context() + try { + await ctx.plugin(MemorySettings) + const fiber = await ctx.plugin(SubagentRuntime, { maxDepth: 4 }) + expect(ctx.subagents.resolveMaxDepth()).toBe(4) + await ctx.settings.update('subagent', { maxDepth: 0 }) + expect(ctx.subagents.resolveMaxDepth()).toBe(0) + expect(ctx.subagents.resolveMaxDepth(2)).toBe(2) + expect(ctx.subagents.resolveMaxDepth('provider-managed')).toBeUndefined() + await expect(ctx.settings.update('subagent', { maxDepth: -0 })).rejects.toThrow() + await expect(ctx.settings.update('subagent', { maxDepth: -1 })).rejects.toThrow() + await expect(ctx.settings.update('subagent', { maxDepth: 1.5 })).rejects.toThrow() + await expect(ctx.settings.update('subagent', { maxActiveSubagents: 0 })).rejects.toThrow() + expect(ctx.subagents.resolveMaxDepth()).toBe(0) + await ctx.settings.replace('subagent', {}) + expect(ctx.subagents.resolveMaxDepth()).toBe(4) + await fiber.dispose() + expect(ctx.settings.describe().some(section => section.ns === 'subagent')).toBe(false) + } finally { + await ctx.fiber.dispose() + } + }) + + it('applies capacity edits to an existing root without stopping resident children', async () => { + const release = Promise.withResolvers() + const adapter = new GatedAdapter(Array.from({ length: 4 }, () => ({ chunks: textResponse('done'), gate: release.promise }))) + const { ctx, parent } = await setupWith(adapter, { maxActiveSubagents: 1 }) + parkParent(ctx, parent) + try { + await ctx.plugin(MemorySettings) + const first = await ctx.subagents.startContinuable(startSpec(parent)) + await expect(ctx.subagents.startContinuable(startSpec(parent))).rejects.toMatchObject({ code: 'ACTIVATION_LIMIT_REACHED' }) + await ctx.settings.update('subagent', { maxActiveSubagents: 2 }) + const second = await ctx.subagents.startContinuable(startSpec(parent)) + await ctx.settings.update('subagent', { maxActiveSubagents: 1 }) + expect(ctx.agents.get(first.childId)).toBeDefined() + expect(ctx.agents.get(second.childId)).toBeDefined() + await expect(ctx.subagents.startContinuable(startSpec(parent))).rejects.toMatchObject({ code: 'ACTIVATION_LIMIT_REACHED' }) + await ctx.settings.update('subagent', { maxActiveSubagents: 3 }) + const third = await ctx.subagents.startContinuable(startSpec(parent)) + release.resolve(undefined) + await Promise.all([first, second, third].map(child => waitNoActivation(ctx, child.childId))) + } finally { + release.resolve(undefined) + await ctx.fiber.dispose() + } + }) + it('defaults to eight live children and reuses capacity after settlement', async () => { const release = Promise.withResolvers() const adapter = new GatedAdapter([ diff --git a/packages/subagent/subagent/tsconfig.json b/packages/subagent/subagent/tsconfig.json index 24e8cb5ef4..8648737494 100644 --- a/packages/subagent/subagent/tsconfig.json +++ b/packages/subagent/subagent/tsconfig.json @@ -76,6 +76,9 @@ }, { "path": "../../util/chunked-list" + }, + { + "path": "../../settings/settings" } ] } diff --git a/packages/subagent/tool-subagent/README.i18n.yaml b/packages/subagent/tool-subagent/README.i18n.yaml index 1490881323..0b0f981342 100644 --- a/packages/subagent/tool-subagent/README.i18n.yaml +++ b/packages/subagent/tool-subagent/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/tool-subagent/README.md -README.md: f2d9eb3a44d84130caca8e29bbe0546e24a76b34 -README.zh.md: 312856983f0e25cd6eb8e508f4c7b9e9db361044 +README.md: 17491098fefea43bd3e9b195ad790a34aa8ef155 +README.zh.md: 5d910784ee88796a66f9c4fefc6e83d62a524ac9 diff --git a/packages/subagent/tool-subagent/README.md b/packages/subagent/tool-subagent/README.md index f2d9eb3a44..17491098fe 100644 --- a/packages/subagent/tool-subagent/README.md +++ b/packages/subagent/tool-subagent/README.md @@ -50,7 +50,7 @@ Load the subagent service, an in-process or remote backend, and this tool; then | `agentOptions` | — | Configured child `provider`, `model`, adapter-owned `reasoningEffort`, and positive `maxTokens` defaults; requires provider `agentOptions` support and overlays any provider-owned route defaults | | `persona` | — | Per-child persona; requires the provider's `persona` capability | | `toolFilter` | — | Per-child global-tool restriction; requires the `toolFilter` capability | -| `maxDepth` | `3` | Absolute delegation-depth cap (`0` forbids delegation); `'provider-managed'` sends no cap to an out-of-process provider | +| `maxDepth` | Host setting (`3`) | Absolute delegation-depth cap (`0` forbids delegation); `'provider-managed'` sends no cap to an out-of-process provider | The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-tool-subagent) is the exhaustive source for every accepted field and its JSDoc. @@ -60,7 +60,7 @@ Under `one-shot` policy, an omitted `run_in_background` waits in the foreground Under `continuable` policy, an omitted or `true` `run_in_background` starts a durable child and returns `started subagent ` without waiting for a result; the runtime delivers one settlement notice when the child's Activation ends, and the optional `send_message` tool sends it more work. Set `run_in_background: false` to wait for the result in the foreground. -`maxDepth` caps recursion (default `3`; `0` forbids delegation) and requires a provider with the `depthLimit` capability; `'provider-managed'` leaves the budget to an out-of-process provider. `persona` and `toolFilter` configure every child when the provider supports them, and the tool stays visible at the cap — each attempted start checks the calling agent's current depth and rejects with an errored result. +`maxDepth` caps recursion (`0` forbids delegation); omission reads the current Host `subagent.maxDepth` setting, initially `3`, at each delegation. A numeric depth requires a provider with the `depthLimit` capability; `'provider-managed'` leaves the budget to an out-of-process provider. `persona` and `toolFilter` configure every child when the provider supports them, and the tool stays visible at the cap — each attempted start checks the calling agent's current depth and rejects with an errored result. ### Selecting a child LLM diff --git a/packages/subagent/tool-subagent/README.zh.md b/packages/subagent/tool-subagent/README.zh.md index 312856983f..5d910784ee 100644 --- a/packages/subagent/tool-subagent/README.zh.md +++ b/packages/subagent/tool-subagent/README.zh.md @@ -50,7 +50,7 @@ kind: "package-reference" | `agentOptions` | — | 配置的子级 `provider`、`model`、适配器所有的 `reasoningEffort` 与正整数 `maxTokens` 默认值;要求提供方支持 `agentOptions`,并会覆盖提供方持有的路由默认值 | | `persona` | — | 每个子 agent 独立的 persona;要求提供方具备 `persona` 能力 | | `toolFilter` | — | 每个子 agent 独立的全局工具限制;要求提供方具备 `toolFilter` 能力 | -| `maxDepth` | `3` | 绝对委派深度上限(`0` 禁止委派);`'provider-managed'` 不向进程外提供方发送上限 | +| `maxDepth` | Host 设置(`3`) | 绝对委派深度上限(`0` 禁止委派);`'provider-managed'` 不向进程外提供方发送上限 | 生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-tool-subagent)是每个受支持字段及其 JSDoc 的穷尽式真源。 @@ -60,7 +60,7 @@ kind: "package-reference" `continuable` 策略下,省略或为 `true` 的 `run_in_background` 会启动一个持久化子 agent,并返回 `started subagent `,不等待结果;子 agent 的 Activation 结束时,运行时投递一条结算通知,可选的 `send_message` 工具会向它发送更多工作。把 `run_in_background` 设为 `false` 可在前台等待结果。 -`maxDepth` 限制递归深度(默认 `3`;`0` 禁止委派),并要求提供方具备 `depthLimit` 能力;`'provider-managed'` 把预算留给进程外提供方。当提供方支持时,`persona` 与 `toolFilter` 会配置每个子 agent;工具在达到上限时仍然可见——每次尝试启动都会检查调用 agent 的当前深度,被拒绝时返回出错的工具结果。 +`maxDepth` 限制递归深度(`0` 禁止委派);省略时,每次委派读取 Host 当前的 `subagent.maxDepth` 设置,初始值为 `3`。数值深度要求提供方具备 `depthLimit` 能力;`'provider-managed'` 把预算留给进程外提供方。当提供方支持时,`persona` 与 `toolFilter` 会配置每个子 agent;工具在达到上限时仍然可见——每次尝试启动都会检查调用 agent 的当前深度,被拒绝时返回出错的工具结果。 ### 选择子级 LLM diff --git a/packages/subagent/tool-subagent/src/index.ts b/packages/subagent/tool-subagent/src/index.ts index cd61f1aa70..7a319967f4 100644 --- a/packages/subagent/tool-subagent/src/index.ts +++ b/packages/subagent/tool-subagent/src/index.ts @@ -91,13 +91,14 @@ export interface Config { deny?: string[] } /** - * Maximum child depth: a non-negative safe integer (default `3`; `0` forbids - * delegation entirely), or `'provider-managed'` to send no cap. A numeric cap + * Maximum child depth: a non-negative safe integer (`0` forbids delegation), + * or `'provider-managed'` to send no cap. A numeric cap * requires the provider's `depthLimit` capability (mount fails loud * otherwise). The provider checks the calling agent's current depth at every * start; the tool remains model-visible so runtime policy owns rejection. * `'provider-managed'` is for an out-of-process provider whose recursion - * budget belongs to the child runtime or its own deployment. + * budget belongs to the child runtime or its own deployment. Omission reads + * the current Host subagent depth setting (default `3`) at each delegation. */ maxDepth?: number | 'provider-managed' } @@ -126,7 +127,7 @@ export const Config: z = z.object({ allow: z.array(z.string()).default(undefined as unknown as string[]), deny: z.array(z.string()).default(undefined as unknown as string[]), }).default(undefined as unknown as { allow: string[]; deny: string[] }), - maxDepth: z.union([z.natural().max(Number.MAX_SAFE_INTEGER), z.const('provider-managed' as const)]).default(3), + maxDepth: z.union([z.natural().max(Number.MAX_SAFE_INTEGER), z.const('provider-managed' as const)]), }) /** Render text blocks from the canonical JSON block array without trusting arbitrary values. */ @@ -326,7 +327,7 @@ export function apply(ctx: Context, config: Config, session?: Session): void { ctx.sessionProjections.register(subagentModelSelectionProjectionDefinition) const assertSubagentProviderConfiguration = (subagentProvider: SubagentProvider): void => { - if (typeof config.maxDepth === 'number' && !subagentProvider.capabilities.depthLimit) { + if (ctx.subagents.resolveMaxDepth(config.maxDepth) !== undefined && !subagentProvider.capabilities.depthLimit) { throw new Error( `tool-subagent: provider "${subagentProvider.name}" cannot enforce maxDepth (no depthLimit capability) — ` + 'set maxDepth: \'provider-managed\' to leave the recursion budget to the provider', @@ -511,7 +512,7 @@ export function apply(ctx: Context, config: Config, session?: Session): void { } } exec.signal.throwIfAborted() - const maxDepth = typeof config.maxDepth === 'number' ? config.maxDepth : undefined + const maxDepth = runtimeCtx.subagents.resolveMaxDepth(config.maxDepth) const request = { label: args.description, prompt: [{ type: 'text', text: args.prompt }] as ContentBlock[], diff --git a/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts b/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts index d7a5923526..5d9cda8dcb 100644 --- a/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts +++ b/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts @@ -23,7 +23,7 @@ import { subagentModelSelectionPolicy, subagentModelSelectionProjectionDefinition, } from '../src/model-selection-state.ts' -import { text } from './harness.ts' +import { callSubagent, text } from './harness.ts' const ALLOWED_MODELS = [{ provider: 'alpha', model: 'fast-model' }] @@ -485,3 +485,30 @@ describe('SubagentModelSelectionConfig', () => { await ctx.fiber.dispose() }) }) + + +it('reads the saved default depth at each delegation without remounting the tool', async () => { + const ctx = await boot(false) + const depths: Array = [] + try { + ctx.subagents.registerProvider({ + name: 'capture-depth', + capabilities: { agentOptions: true, outputSchema: true, depthLimit: true, toolFilter: true, persona: true }, + inheritsParentContext: false, + start: async (request) => { + depths.push(request.maxDepth) + return { id: SessionId(`depth-${depths.length}`), localAgent: undefined, + result: Promise.resolve({ output: [], stopReason: 'completed' as const }), dispose: async () => {} } + }, + }) + await ctx.plugin(tool, { provider: 'capture-depth' }) + await callSubagent(ctx, { description: 'first', prompt: 'work' }) + await ctx.settings.update('subagent', { maxDepth: 5 }) + await callSubagent(ctx, { description: 'second', prompt: 'work' }) + await ctx.settings.update('subagent', { maxDepth: 0 }) + await callSubagent(ctx, { description: 'disabled', prompt: 'work' }) + expect(depths).toEqual([3, 5, 0]) + } finally { + await ctx.fiber.dispose() + } +}) diff --git a/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts b/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts index b90312c259..2516446881 100644 --- a/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts +++ b/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts @@ -323,7 +323,7 @@ describe('dsh-tool-subagent', () => { }, }) // Direct apply with only `provider` — no toolName, no agentOptions. - tool.apply(ctx, { provider: 'bare' }) + tool.apply(ctx, { maxDepth: 'provider-managed', provider: 'bare' }) await new Promise(r => setTimeout(r, 10)) expect(ctx.tools.schemas().some(s => s.name === 'subagent')).toBe(true) @@ -1028,7 +1028,7 @@ describe('dsh-tool-subagent background mode', () => { inheritsParentContext: false, start: async () => { throw new Error('setup failed') }, }) - tool.apply(ctx, { provider: 'broken-start', toolName: 'subagent_broken' }) + tool.apply(ctx, { maxDepth: 'provider-managed', provider: 'broken-start', toolName: 'subagent_broken' }) const started = await ctx.tools.execute({ signal: testToolSignal, @@ -1059,7 +1059,7 @@ describe('dsh-tool-subagent background mode', () => { request.signal.addEventListener('abort', () => { reject(new Error('startup aborted')) }, { once: true }) }), }) - tool.apply(ctx, { provider: 'pending-start', toolName: 'subagent_pending' }) + tool.apply(ctx, { maxDepth: 'provider-managed', provider: 'pending-start', toolName: 'subagent_pending' }) await ctx.tools.execute({ signal: testToolSignal, @@ -1101,7 +1101,7 @@ describe('dsh-tool-subagent background mode', () => { }, { once: true }) }), }) - tool.apply(ctx, { provider: 'broken-start-rollback', toolName: 'subagent_broken_rollback' }) + tool.apply(ctx, { maxDepth: 'provider-managed', provider: 'broken-start-rollback', toolName: 'subagent_broken_rollback' }) await ctx.tools.execute({ signal: testToolSignal, @@ -1154,7 +1154,7 @@ describe('dsh-tool-subagent background mode', () => { }, }) // Direct apply preserves omitted agentOptions instead of applying schema defaults. - tool.apply(ctx, { provider: 'hanging', toolName: 'subagent_hang' }) + tool.apply(ctx, { maxDepth: 'provider-managed', provider: 'hanging', toolName: 'subagent_hang' }) const startOne = await ctx.tools.execute({ signal: testToolSignal, callId: ToolCallId('h1'), name: 'subagent_hang', arguments: { description: 'one', prompt: 'p', run_in_background: true }, agent: parent }) const startTwo = await ctx.tools.execute({ signal: testToolSignal, callId: ToolCallId('h2'), name: 'subagent_hang', arguments: { description: 'two', prompt: 'p', run_in_background: true }, agent: parent }) @@ -1371,7 +1371,7 @@ describe('background preflight failure (no orphaned child, by construction)', () } }, }) - tool.apply(ctx, { provider: 'probe', toolName: 'subagent_probe' }) + tool.apply(ctx, { maxDepth: 'provider-managed', provider: 'probe', toolName: 'subagent_probe' }) const result = await ctx.tools.execute({ signal: testToolSignal, diff --git a/packages/test-support/session-snapshot/tests/fixtures/subagent-activation-limit.ts b/packages/test-support/session-snapshot/tests/fixtures/subagent-activation-limit.ts index 14f921ee96..34c40de83d 100644 --- a/packages/test-support/session-snapshot/tests/fixtures/subagent-activation-limit.ts +++ b/packages/test-support/session-snapshot/tests/fixtures/subagent-activation-limit.ts @@ -2,7 +2,7 @@ import type { Context } from '@deepseek-ai/cordis' export const name = 'subagent-activation-limit' -export const inject = ['agents'] +export const inject = ['agents', 'settings', 'subagents'] /** Order parent admission and child completion without elapsed-time assumptions. */ export function apply(ctx: Context): void { @@ -13,6 +13,7 @@ export function apply(ctx: Context): void { }) ctx.on('agent/pre-step', async ({ agent }, next) => { if (agent.session.header.parentSession !== undefined) await parentClosed.promise + else await ctx.settings.update('subagent', { maxActiveSubagents: 1 }) return next() }) } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a1fb756407..b618eb8758 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -10373,6 +10373,9 @@ importers: '@deepseek-ai/dsh-session-query': specifier: workspace:^ version: link:../../session-query/session-query + '@deepseek-ai/dsh-settings': + specifier: workspace:^ + version: link:../../settings/settings '@deepseek-ai/dsh-storage': specifier: workspace:^ version: link:../../storage/storage diff --git a/snapshots/sdk/subagent-activation-limit/cordis.snapshot.yml b/snapshots/sdk/subagent-activation-limit/cordis.snapshot.yml index 52aa1e1b84..571a3f2e07 100644 --- a/snapshots/sdk/subagent-activation-limit/cordis.snapshot.yml +++ b/snapshots/sdk/subagent-activation-limit/cordis.snapshot.yml @@ -55,4 +55,4 @@ - id: subagent name: '@deepseek-ai/dsh-subagent' config: - maxActiveSubagents: 1 + maxActiveSubagents: 8 diff --git a/snapshots/sdk/subagent-activation-limit/cordis.yml b/snapshots/sdk/subagent-activation-limit/cordis.yml index e9764eca90..04940d1541 100644 --- a/snapshots/sdk/subagent-activation-limit/cordis.yml +++ b/snapshots/sdk/subagent-activation-limit/cordis.yml @@ -1,7 +1,7 @@ - id: subagent name: '@deepseek-ai/dsh-subagent' config: - maxActiveSubagents: 1 + maxActiveSubagents: 8 - insert: - id: subagent-activation-limit