From 55e356d60fc392edbd3ed7386a29cc43c7944175 Mon Sep 17 00:00:00 2001 From: Shigma Date: Tue, 3 Nov 2026 13:49:28 +0800 Subject: [PATCH 001/450] docs(vendor): drop the rc.11 plan and correct upstream pins --- vendor/README.md | 21 +++---- vendor/cordis-rc11-upgrade-plan.md | 93 ------------------------------ 2 files changed, 9 insertions(+), 105 deletions(-) delete mode 100644 vendor/cordis-rc11-upgrade-plan.md diff --git a/vendor/README.md b/vendor/README.md index 9020f5dcb6..c3a4c8e774 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -6,23 +6,19 @@ All vendored packages use the **`@deepseek-ai` scope** (`cordis` → `@deepseek- This file covers the manifest, the local-modification log, and the procedure for **updating** an existing vendored package. To **add a new** one, see the cookbook guide: [docs/cookbook/adding-a-vendored-package.md](../docs/cookbook/adding-a-vendored-package.md). -The proposed [Cordis rc.11 upgrade plan](cordis-rc11-upgrade-plan.md) records the package scope, PR dependencies and intended disposition of the local modifications. - ## Manifest -Upstream workspace: `cordis-workspace` (local checkout: `~/repos/cordis-workspace`). - | Directory | npm name | Upstream name | Version | Upstream repo | Commit | |---|---|---|---|---|---| -| `cosmokit/` | `@deepseek-ai/cosmokit` | `cosmokit` | 1.8.1 | https://github.com/deepseek-harness/cosmokit | `16f6fc058ade66e8ac5da0033d35a8d0f279f544` | -| `schemastery/` | `@deepseek-ai/schemastery` | `schemastery` | 3.18.0 | https://github.com/deepseek-harness/schemastery (`packages/core`) | `e67cee00ad725bd1534aee930a979ea3eec6f698` | +| `cosmokit/` | `@deepseek-ai/cosmokit` | `cosmokit` | 1.8.1 | https://github.com/shigma/cosmokit | `02e691c5aa7f37f6e0b1cee7ee8f4a21c2e34507` | +| `schemastery/` | `@deepseek-ai/schemastery` | `schemastery` | 3.18.0 | https://github.com/shigma/schemastery (`packages/core`) | `cf0b7e5481d0e31d10cdc30bc45c09366c332f27` | | `cordis/` | `@deepseek-ai/cordis` | `cordis` | 4.0.0-rc.11 | https://github.com/cordiverse/cordis (`packages/core`) | `0b96d9fd517b998e44e2209560c9e5f0671ce933` | | `loader/` | `@deepseek-ai/cordis-plugin-loader` | `@cordisjs/plugin-loader` | 1.0.0-rc.8 | https://github.com/cordiverse/cordis (`packages/loader`) | `0b96d9fd517b998e44e2209560c9e5f0671ce933` | | `include/` | `@deepseek-ai/cordis-plugin-include` | `@cordisjs/plugin-include` | 1.1.1 | https://github.com/cordiverse/cordis (`packages/include`) | `0b96d9fd517b998e44e2209560c9e5f0671ce933` | -| `group/` | `@deepseek-ai/cordis-plugin-group` | `@cordisjs/plugin-group` | 1.0.0 | https://github.com/deepseek-harness/cordis (`packages/group`) | `abb0a307cb1d3b0947f455d590cf5ba922d4caa4` | -| `timer/` | `@deepseek-ai/cordis-plugin-timer` | `@cordisjs/plugin-timer` | 1.1.4 | https://github.com/cordiverse/cordis (`packages/timer`) | `0b96d9fd517b998e44e2209560c9e5f0671ce933` | -| `hmr/` | `@deepseek-ai/cordis-plugin-hmr` | `@cordisjs/plugin-hmr` | 1.0.15 | https://github.com/deepseek-harness/cordis (`packages/hmr`) | `abb0a307cb1d3b0947f455d590cf5ba922d4caa4` | -| `logger-console/` | `@deepseek-ai/cordis-plugin-logger-console` | `@cordisjs/plugin-logger-console` | 1.0.0 | https://github.com/deepseek-harness/cordis (`packages/logger-console`) | `abb0a307cb1d3b0947f455d590cf5ba922d4caa4` | +| `group/` | `@deepseek-ai/cordis-plugin-group` | `@cordisjs/plugin-group` | 1.0.0 | https://github.com/cordiverse/cordis (`packages/group`) | `01b396240ce47cf2779c40af9bc445bb748fe112` | +| `timer/` | `@deepseek-ai/cordis-plugin-timer` | `@cordisjs/plugin-timer` | 1.1.4 | https://github.com/cordiverse/cordis (`packages/timer`) | `01b396240ce47cf2779c40af9bc445bb748fe112` | +| `hmr/` | `@deepseek-ai/cordis-plugin-hmr` | `@cordisjs/plugin-hmr` | 1.0.15 | https://github.com/cordiverse/cordis (`packages/hmr`) | `ed8a7755c26a27a72064a21dea036ad1d1d6833c` | +| `logger-console/` | `@deepseek-ai/cordis-plugin-logger-console` | `@cordisjs/plugin-logger-console` | 1.0.0 | https://github.com/cordiverse/cordis (`packages/logger-console`) | `01b396240ce47cf2779c40af9bc445bb748fe112` | Third-party dependencies of the vendored packages stay on npm: `@standard-schema/spec`, `js-yaml`, `chokidar`, `picomatch`, `@babel/code-frame`, `supports-color`, `node-addon-require-builtin`. @@ -31,13 +27,14 @@ Intentionally **not** vendored (verified unused by this set): `reggol`, `@cordis ## Local modifications Keep this log exhaustive — every divergence from upstream must be listed. Each entry has a stable ID: remove an entry when its divergence no longer exists, and never renumber or reuse IDs. The next new entry is V28. + - **V1 · `hmr/src/index.ts`**: removed the `./locales/en-US.yml` / `./locales/zh-CN.yml` imports, the `.i18n({...})` call on the `Config` schema, and the `src/locales/` directory. Rationale: those imports require a runtime YAML loader hook (`@cordisjs/unyaml`) that we do not vendor; the i18n texts only localize config descriptions. - **V2 · All `package.json` files**: regenerated for Harness releases with scoped names, release versions, publication metadata, precise bundled-runtime and `lib/types/**/*.d.ts` / `.d.ts.map` file entries, source exports where applicable, and declaration metadata pointing at `lib/types`. References within the vendored set use `workspace:~`. HMR declares `esbuild` as a direct dev dependency for its imported `BuildFailure` type, and Loader requires `node-addon-require-builtin@^0.1.4` to match published app runtimes. - **V3 · All `tsconfig.json` files**: regenerated to extend the repo-root `tsconfig.base.json`, emit TypeScript intermediates to `lib/types`, and declare project references. - **V4 · Vendored TypeScript source internal specifiers**: changed local relative imports/exports from upstream's specifier shape to explicit `.ts` specifiers so TypeScript rewrites emitted JS to `.js` while declarations keep explicit, NodeNext-safe `.ts` specifiers. This includes `loader/src/config/isolate.ts` using `declare module './entry.ts'`. Type-only dependencies use `import type` or inline `type` modifiers so ESM output does not retain erased interfaces. - **V5 · `schemastery/tsdown.config.ts` and `logger-console/tsdown.config.ts`**: ours, not upstream files — per-package build-shape overrides (dual ESM+CJS output; separate node/browser entries) for the repo-root tsdown build. They read the JS emitted under `lib/types` and then write the publish runtime entries under `lib/`. Like the regenerated tsconfigs, they are not part of the upstream sync surface. - **V6 · `cordis/src/fiber.ts` lifecycle hardening**: locally closes three reentrant disposal gaps. An effect's owner-list wrapper is registered before its setup body runs, so an unload begun from inside setup awaits setup and every collected cleanup; synchronous setup failure removes the wrapper and rolls back collected cleanup. Async cleanup stays owner-visible until quiescence, and Cordis's internal effect composition joins an already-running cleanup while repeated public disposer calls retain their upstream single-shot result. Effect creation is rejected while the owner is `UNLOADING` (while `PENDING` and `LOADING` remain legal), preventing cleanup-time registrations from escaping the unload snapshot. Child fibers register and receive their parent-owned disposer before `internal/plugin` publication, resolve dependency declarations added by that notification before activation, drain effects attached while pending, and contain teardown-notification failures per observer so one callback cannot starve peers or interrupt ownership cleanup. -- **V7 · Cordis, Loader and Timer JSDoc enrichment**: added `@param`/`@returns` tags and contract documentation (disposal semantics, waterfall veto, bail conditions, error cases) across the public plugin-author surface — `Context` (class, statics, and the `Context` interface properties incl. `root`), module re-exports, shared utility helpers, `EventsService`, `Fiber`, `RegistryService`, `ReflectService`, `Service`, `LoggerService` and their `declare module './context.ts'` overloads. Loader documentation covers `loader/src/{index,internal,config/entry,config/group,config/isolate,config/tree,config/utils}.ts`, including entry ownership, tree mutation methods, and the `!!js` discriminator. The upstream `EventsService.dispatch()` deprecation annotation is omitted: DSH enumerates callbacks to contain each observer failure independently, which the typed dispatch methods do not provide. Timer retains its local class and helper summaries; its README is local documentation because the upstream package has none. Comment-only; no code changes. Motivation: the website API-reference generator renders these docs and hard-errors on undocumented members. Retire this entry when the enrichment is upstreamed to the fork. +- **V7 · JSDoc enrichment**: added `@param`/`@returns` tags and contract documentation (disposal semantics, waterfall veto, bail conditions, error cases) across the public plugin-author surface — `Context` (class, statics, and the `Context` interface properties incl. `root`), module re-exports, shared utility helpers, `EventsService`, `Fiber`, `RegistryService`, `ReflectService`, `Service`, `LoggerService` and their `declare module './context.ts'` overloads. Loader documentation covers `loader/src/{index,internal,config/entry,config/group,config/isolate,config/tree,config/utils}.ts`, including entry ownership, tree mutation methods, and the `!!js` discriminator. The upstream `EventsService.dispatch()` deprecation annotation is omitted: DSH enumerates callbacks to contain each observer failure independently, which the typed dispatch methods do not provide. Timer retains its local class and helper summaries; its README is local documentation because the upstream package has none. Cosmokit and Schemastery add summaries to their exported helpers, types and namespaces, logger-console to its exporters and config namespace, and HMR to its build-failure logger in `hmr/src/error.ts`. Comment-only; no code changes. Motivation: the website API-reference generator renders these docs and hard-errors on undocumented members. Retire this entry when the enrichment is upstreamed. - **V9 · `hmr/src/index.ts` module-watcher readiness and native paths**: realpath the existing watch base, classify framework modules and attach listeners before reporting readiness, and compare config paths using both canonical and configured spellings. This preserves Node module-cache identity across Windows short-name paths and filesystem aliases. The main watcher uses `ignoreInitial: true` so startup reads do not trigger another refresh; exact profile patch watching is owned by `packages/boot/hmr/src/watch-config.ts`. The Include change listener logs a rejected `Include.refresh()` instead of leaving the rejection unhandled; the rejection reports unsaved runtime changes while Include keeps its running tree. Covered by `packages/boot/hmr/tests/watch-config.spec.ts` and `scripts/cordis-vendor-hmr-include.spec.ts`. - **V10 · Vendored Node-compatible TypeScript**: marked erased imports explicitly across `cordis`, `loader`, `include`, `hmr`, and `schemastery` so Node's native TypeScript transform does not request types as runtime exports. Schemastery's source uses an ESM default export and its package declares `type: module`. Conditional exports select `.mjs` for import and `.cjs` for require; without them, concurrent imports under module-hook hosts reach the CJS entry and can race its require of ESM Cosmokit (`ERR_REQUIRE_ESM_RACE_CONDITION`). - **V11 · Include patch and YAML exports**: `include/src/index.ts` exports upstream `applyPatches` as `applyEntryPatches` and the `!!js` YAML dialect as `entryListSchema`, so `dsh --dump-config` composes entries with the same algorithm that mounting uses. Covered by `packages/boot/app-boot/tests/config-reload.spec.ts` and `scripts/cordis-entry-commit.spec.ts`. @@ -63,7 +60,7 @@ Relative to the resolver source in Cordis `v4.0.0-rc.11`: To update a vendored package from upstream: -1. In the upstream workspace, note `git rev-parse HEAD` of the relevant submodule. +1. In the upstream repository listed in the manifest, check out the release tag or commit to sync and note its full commit SHA. 2. Copy the package's `src/` (and `bin.js`, `README.md`, `LICENSE` if changed) over the vendored directory. 3. Re-apply the local modifications listed above (or drop them if upstream made them unnecessary — update the log either way). 4. Update the version and commit hash in the manifest table. diff --git a/vendor/cordis-rc11-upgrade-plan.md b/vendor/cordis-rc11-upgrade-plan.md deleted file mode 100644 index 7833cf3514..0000000000 --- a/vendor/cordis-rc11-upgrade-plan.md +++ /dev/null @@ -1,93 +0,0 @@ -# Cordis rc.11 vendor upgrade plan - -Status: proposed - -## Problem - -The upgrade starts from the [vendored](README.md) baselines Cordis core 4.0.0-rc.7, Loader 1.0.0-rc.5, Include 1.0.4, HMR 1.0.15 and Timer 1.1.2, with 24 local-modification entries. [Cordis v4.0.0-rc.11](https://github.com/cordiverse/cordis/releases/tag/v4.0.0-rc.11) incorporates some fixes and replaces other mechanisms. Updating every package and retiring every patch in one change would combine configuration, persistence, lifecycle and module-replacement decisions. - -DSH also has consumers that upstream Cordis does not own. Volatile configuration fields are stable references updated without restarting plugins; the settings UI reads their live values. A profile selects ordered plugin bundles and configuration overrides. [DSH HMR](../packages/boot/hmr/README.md) coordinates module replacement and profile changes through `ctx.hmr`. An entry's module namespace is its raw import result, retained before selecting `default` or `apply` so HMR can identify the module already loaded. These consumers must remain usable at every merge point. - -## Proposal - -Keep source vendoring and stage the upgrade as independently reviewable PRs, each covering a complete concern with its producers and consumers. Upgrade Core with the minimum cross-package compatibility changes, then complete Loader, Include and vendor HMR separately. Retire an existing patch when its replacement is adopted and verified; retain independently applicable patches until their behavior has a replacement. PR 0 records this plan only. It does not approve the open runtime decisions or implement the upgrade. - -### Package scope - -| Package | Target from the rc.11 tag | Treatment | -|---|---|---| -| `vendor/cordis` | 4.0.0-rc.11 | Upgrade with the Core compatibility slice. | -| `vendor/loader` | 1.0.0-rc.8 | Import required slices first; complete the package after resolution and change reporting land. | -| `vendor/include` | 1.1.1 | Separate patch composition from journal adoption. | -| `vendor/hmr` | 1.1.1 | Upgrade independently of the Include journal. | -| `vendor/timer` | 1.1.4 | Upgrade independently of Core. | -| `vendor/group` | Keep the existing pin | Its entry source matches the tag after rescoping. The Group implementation lives in Loader and still requires migration. | -| `vendor/logger-console` | Keep the existing pin | All three source files match the tag after normalizing scope, relative import extensions and comments. Core's logger changes remain part of the Core upgrade. | -| `vendor/cosmokit`, `vendor/schemastery` | Keep the existing pins | Retain the volatile extensions; their upstream upgrades are outside this plan. | - -The comparison above checks the current vendored source against the release tag; it does not assume equal version numbers imply equal code. DSH package versions, exports and build settings remain governed by the repository. A partially synchronized Loader, Include or HMR keeps its old manifest baseline and records the imported upstream slice in the local-modification log. Advance the package baseline only when the complete package has been reconciled, with remaining differences recorded explicitly. - -### PR dependencies - -The identifiers below are plan labels, not GitHub issue numbers. Preconditions are merge requirements. Independent PRs can be developed and reviewed concurrently; a dependent PR can start against the proposed changes before its predecessors merge, but must validate the actual combined result before merging. - -`Vn` below is the stable ID of an entry in the [local-modification log](README.md#local-modifications), not a PR; a retired ID no longer appears in the log. **Retire** means the upstream implementation replaces the local difference; **partial** means some behavior still needs a local adaptation; **retain** means the requirement remains; **prepare** does not retire a patch. These are proposed outcomes, confirmed only by the owning PR's tests. - -| PR | Scope | Prerequisite PRs | Existing vendor modifications | Required evidence | -|---|---|---|---|---| -| 0 | This plan, package comparison and open decisions. | None | None retired; records the proposed disposition. | Documentation checks; no runtime changes. | -| 1 | Define access to raw config, candidate resolution and the active instance's effective config, and migrate settings, Config Editor, volatile updates and HMR readers together. Initially delegate to the old framework fields. | 0 | Prepare V15 (lazy/raw config) and V22 (volatile); retire neither yet. | Preserve existing objects, validation, settings and volatile behavior. Candidate validation does not replace the active instance's references; introduce no dependency from vendor code to DSH packages. | -| 2 | Add upstream-compatible `hmr.watch()` to both HMR providers with compatible typing, migrate the existing Include to explicit registration, and remove the equivalent Include scans. Use DSH HMR's existing coordination queue. | 0 | Adapt V9's config-path matching to explicit watches; retain its readiness and native-path requirements. | Callback ordering, disposal, explicit paths and `root: []` under the old Core; one Include refresh per change under either provider. Preserve profile watching and both module-replacement algorithms. | -| 3 | Upgrade Timer to 1.1.4, retaining DSH locale resources and build metadata. | 0 | Retain V24 (display metadata); no logged runtime patch retired. | Concurrent interval reads, throttle cancellation and void return types; check callers using the old Core. | -| 4a | Upgrade Core to rc.11 with the minimum Loader, Include and HMR compatibility slice described below. | 1 | Retire V12 (activation observer), V21 (logger disposer) and, after canonical-fiber audits, V20 (Entry identity workaround). Partial V6 (lifecycle) and V15 (config model). Retain/adapt V22 and V23 (module namespace). | Config resolution, volatile identity, service isolation, dependent-before-provider teardown, retained effect regressions and application startup. | -| 4b | Import Loader's project-relative bare-specifier resolver, runtime API detection and fallback when Node internals are absent. | 0 | Retire V19: upstream now detects the internal loader by its available APIs. | Resolve in the config project's package scope, retain subpaths, handle read-only helper creation and test Node 24's older v1 API. | -| 4c | Complete Loader's `EntryChange` / `commit(change)` reporting and remaining changes, and upgrade Include to its 1.1.1 journal implementation in the same PR. Both HMR providers keep finding Include through their existing scans; keep `applyEntryPatches` and `entryListSchema` exports and in-memory no-op commits. | 4a, 4b | Retire V18 (`disabled` expressions), V8 (old refresh implementation) and V13 (`writeTask` type). Partial V11: retire the duplicate patch algorithm and insert-index fix; retain public exports. Partial V14: replace the write queue; retain rejection while the journal contains unsaved changes. Retain/adapt V22, including the schema receiver fix, V23 and the V15 child-expression marker. | Create, move, remove and self-update reports; no false self-disposal writes; later patches address inserted rows; stable ids for anonymous entries; file/runtime conflict handling, patch-owned writes, shutdown results and nested expressions; cloning and config dumps agree with mounting. | -| 4e | Complete vendor HMR's upgrade to 1.1.1, preserving required local path, readiness and explicit-watch behavior. | 2, 3, 4a | Partial V9: adopt upstream ordering and path handling where equivalent; retain explicit readiness and realpath gaps. Retain V1 (no YAML locale imports). | Three-stage module replacement, nested entries, disabled/removed entries, explicit watches and the existing local path cases. | -| 4f | Register the journal Include through the explicit watch adopted in PR 2 and remove the remaining Include scans. | 2, 4c | Adapt V9's config-path matching to the journal Include. | One coordinated refresh per change under either HMR provider; profile watching unchanged. | - -Shared integration differences remain in every affected sync: V2 (manifests), V3 (TypeScript projects), V4/V10 (imports and Node-compatible modules), V5 (build overrides), V7 (API documentation), V16 (published Core source) and V17 (scope). Untouched packages retain them without edits. V6 only loses the stale-epoch guard already supplied upstream; its remaining ownership and cleanup guarantees stay. V15 replaces the old raw/effective-config and event implementation, but the Include child-expression behavior remains local. V22 is not upstreamed by this release, including its schema-bound `simplify` call. - -After PR 0, PRs 1, 2, 3 and 4b have no implementation dependency on one another. Core depends on configuration preparation; it does not depend on Timer. Loader completion and vendor HMR can proceed independently after Core. Include journal adoption is part of Loader completion; PR 4f only connects that Include to PR 2's explicit watches and does not depend on the new vendor HMR replacement algorithm, so PRs 4e and 4f can merge in either order. No single GitHub stack should impose a dependency between unrelated branches. Shared files such as the vendor manifest may still require merge-conflict resolution. - -### Minimum Core compatibility slice - -PR 4a must migrate every caller of the changed Core APIs in the same PR, including callers outside vendor. This is a complete Core upgrade with local patches, paired with selected Loader changes; it is not a claim that Loader already equals 1.0.0-rc.8. - -- Adopt upstream raw `Fiber.config`, `internal/config(fiber, next)`, `internal/commit` and the new `internal/update` arguments and awaited result. Update the config accessors, provider hooks, boot observers and old Include's update listener together. The temporary commit listener writes through the old tree writer until PR 4c. -- Carry the required Loader entry/context awaiting chain, activation-failure observer and isolation changes with Core's `Impl.ctx`, `Impl.isolate`, `committed` and dependent tracking. Update direct implementation readers such as the preset registry. Include Group behavior owned by `vendor/loader/src/config/group.ts`; do not confuse it with the unchanged `vendor/group` entry package. Before retiring V20, ensure volatile updates and every other direct lifecycle-field access use the canonical `fiber.ctx.fiber`. -- Keep Include's nested-entry expressions literal until the owning child resolves them. Keep the namespace field needed by DSH HMR and preserve active volatile references through the agreed config mechanism. Update raw-config access in both HMR implementations without replacing the DSH module-replacement policy. -- Reapply the still-needed effect ownership, reentrant disposal and observer-containment guarantees to the new Core lifecycle. Remove patches already supplied by the imported Core source. Verify the combination with provider/dependent teardown before treating the compatibility slice as complete. - -Module resolution, structured tree-change reporting, journal reconciliation and the new vendor HMR algorithm are not prerequisites for these Core interfaces. Their PRs remain separate unless executable compatibility tests expose an additional dependency; amend this plan before broadening a PR silently. - -### Temporary compatibility code - -PR 4c changes tree mutation producers to `commit(change)` and adopts the journal Include in the same PR: upstream `patch.ts` clones file and inserted entries, while the old Include relied on sharing entry objects with the running tree for its cached data and generated ids. In-memory trees, including `PresetTree`, implement a no-op commit. Until PR 4f, both HMR providers find the journal Include through their existing scans and call its `refresh()`. - -The public patch export may remain an alias; it must not retain a second algorithm. Every temporary divergence has an owning introduction PR and a named removal PR. No runtime version detection or second Core event protocol is planned. - -PR 2 moves Include refresh ownership in one step: both HMR providers expose `watch()`, the existing Include registers its callback, and both providers stop their equivalent Include scans. The upstream HMR source no longer performs that scan, so importing it before migrating the Include consumer would lose config refresh. Moving the complete watch concern first avoids a temporary scan adapter and makes the later module-replacement and persistence decisions independent. - -### Decisions owned by individual PRs - -| Decision | Owning PR | Proposal and unresolved choice | -|---|---|---| -| Active effective config | 1, 4a | Store or expose the object actually supplied to the current instance. Resolving a candidate through `internal/config` must not overwrite it. Decide the publication point and invalidation rules before switching Core; a WeakMap alone does not establish those rules. | -| Persistence outcome | 4c | Use the journal's retry and reconciliation mechanism. Explicit `flush()` and `stop()` reject while changes remain unsaved; later successful retries clear previous errors. Keep this local adaptation minimal. | -| Nested config interpolation | 4a, 4c | Preserve child-owned expression evaluation. Keep the existing Include marker initially; any refinement that permits interpolation of Include's own fields while excluding child lists is a separate behavior change. | -| HMR replacement failure | 4e | Adopt upstream behavior for vendor HMR. Preserve DSH HMR's current source-reload rollback policy in this series; replacing that policy requires its own proposal and tests. | -| Effect cleanup guarantees | 4a | Retain guarantees not supplied by rc.11. Further upstreaming or retirement is separate work, not a prerequisite for reaching the release baseline. | - -## Acceptance criteria - -- Every implementation PR leaves supported applications usable and passes checks appropriate to its changes. A later PR may not be required to repair an earlier PR's startup, types, persistence or teardown. -- Each source-vendor update follows the [sync procedure](README.md#sync-procedure), including `pnpm run test` and `pnpm run build`, and updates its own manifest, local-modification log, affected documentation and generated references. The [pre-push workflow](../.agents/skills/dsh-pre-push-checks/SKILL.md) selects additional focused checks. Documentation freshness is not deferred to a final cleanup PR. -- Every changed behavior has an explicit decision and focused regression coverage. Tests for an intentionally superseded behavior change with its implementation and explain the new expectation. -- Once all implementation PRs are complete, Core, Loader, Include, vendor HMR and Timer use their selected rc.11-tag sources with enumerated remaining patches. Group, logger-console, Cosmokit and Schemastery keep their existing pins. All temporary writer and config adapters have been removed or reduced to the agreed permanent accessors. -- Final integration verification exercises settings and volatile updates, profile recomposition, both HMR providers, Include persistence and representative built application launches. This is an acceptance checkpoint, not an otherwise empty PR. - -## Risks - -PR 4a remains the largest necessary compatibility change: Core's service lifetime and configuration model cross repository package boundaries. The minimum slice is based on source inspection, not a completed migration experiment. Focused tests may identify additional inseparable changes. - -Intermediate Loader, Include and HMR copies intentionally combine an old baseline with documented upstream slices. Missing slice records would make a later sync unsafe. Deferred config, candidate validation, journal writes and asynchronous disposal must be tested in combination rather than inferred from independently passing unit cases. A new Include's type dependency on HMR must not force both concrete providers into the same incompatible `Context.hmr` declaration. From 94829d14f37e99dba7a4aecf5c6286841633c707 Mon Sep 17 00:00:00 2001 From: Yif <877193178@qq.com> Date: Wed, 4 Nov 2026 19:17:37 +0800 Subject: [PATCH 002/450] feat(ui): add inline reasoning controls to model picker Keep model and effort selection in the first-level menu, move Team settings into a detail page, and preserve keyboard focus during selection and pending saves. Add localized effort tooltips, theme-stable slider thumbs, and focused keyboard and browser regression coverage. --- apps/web/tests/agent-team-panel.e2e.ts | 230 +++++--- apps/web/tests/declared-reasoning.e2e.ts | 281 +++++++--- .../tests/deepseek-messages-settings.e2e.ts | 17 +- apps/web/tests/default-model.e2e.ts | 40 +- .../pointer-menu.expected.md | 2 +- .../declared-reasoning/ui.expected.md | 9 +- .../picker.expected.md | 2 +- .../expected/default-model/search.expected.md | 2 +- apps/web/tests/model-menu-observer.e2e.ts | 55 +- apps/web/tests/plugin-manager.e2e.ts | 1 + .../collaboration.zh.expected.md | 5 +- .../agent-team-panel/info.expected.md | 13 +- .../client/ui-agent-team/README.i18n.yaml | 8 +- packages/client/ui-agent-team/README.md | 4 +- packages/client/ui-agent-team/README.zh.md | 4 +- .../src/client/TeamModeToggle.module.css | 78 ++- .../src/client/TeamModeToggle.tsx | 80 ++- .../ui-agent-team/src/client/locales.ts | 24 +- .../client/ui-agent-team/src/client/mount.ts | 9 +- .../tests/browser-plugin.client.spec.ts | 22 +- .../tests/team-mode.client.spec.tsx | 177 +++--- .../ui-model-selection/README.i18n.yaml | 20 +- packages/client/ui-model-selection/README.md | 22 +- .../client/ui-model-selection/README.zh.md | 22 +- .../src/client/EffortSlider.module.css | 141 +++++ .../src/client/EffortSlider.tsx | 122 +++++ .../src/client/ModelSelect.module.css | 75 ++- .../src/client/ModelSelect.tsx | 275 +++++----- .../ui-model-selection/src/client/index.ts | 1 + .../ui-model-selection/src/client/locales.ts | 16 + .../ui-model-selection/src/client/slots.ts | 34 +- .../tests/effort-slider.client.spec.tsx | 214 ++++++++ .../tests/model-menu-tab.client.spec.tsx | 187 +++++++ .../tests/model-select.client.spec.tsx | 508 +++++++++++++----- .../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/Switch.tsx | 11 +- .../tests/switch.client.spec.tsx | 33 ++ .../ui-theme/src/styles/design-platform.css | 4 + .../src/client/slot-catalog.ts | 59 +- 41 files changed, 2148 insertions(+), 667 deletions(-) create mode 100644 packages/client/ui-model-selection/src/client/EffortSlider.module.css create mode 100644 packages/client/ui-model-selection/src/client/EffortSlider.tsx create mode 100644 packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx create mode 100644 packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx diff --git a/apps/web/tests/agent-team-panel.e2e.ts b/apps/web/tests/agent-team-panel.e2e.ts index a68c1908a7..e8477cfba4 100644 --- a/apps/web/tests/agent-team-panel.e2e.ts +++ b/apps/web/tests/agent-team-panel.e2e.ts @@ -39,6 +39,19 @@ const RECEIPT_LOCALES = [ type ReceiptLocale = typeof RECEIPT_LOCALES[number] +async function openTeamSettings(page: Page, chinese = false): Promise { + const trigger = page.getByRole('button', { name: chinese ? /^选择模型/u : /^Select model/u }) + await trigger.click() + await expect.poll(() => trigger.getAttribute('aria-expanded')).toBe('true') + await page.getByRole('menuitem', { name: chinese ? /^智能体团队协作 /u : /^Agent teamwork /u }).click() +} + +async function closeModelMenu(page: Page): Promise { + const trigger = page.getByRole('button', { name: /^(Select model|选择模型)/u }) + if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() + await expect.poll(() => trigger.getAttribute('aria-expanded')).toBe('false') +} + async function seedTeamConversation(page: Page, scaffold: WebScaffold): Promise { const agent = scaffold.ctx.agents.list()[0] if (agent === undefined) throw new Error('connected Team workspace did not create an Agent') @@ -114,81 +127,148 @@ describe('web e2e: agent teamwork panel', () => { await scaffold?.close() }) - it('explains agent teamwork on hover and focus without changing the Session selection', async () => { + it('shows the explanation and switch only on the second page and returns to the summary', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-team-info')) - await page.getByRole('button', { name: /^Select model/u }).click() - const info = page.getByRole('button', { name: 'About agent teamwork', exact: true }) - const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) - const tooltip = page.getByRole('tooltip') - await info.hover() - await tooltip.waitFor({ state: 'visible' }) - await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'info.expected.md'), await captureStableAria(page, '[role="tooltip"]', scaffold.workspaceCwd), MODE) - expect(await toggle.getAttribute('aria-checked')).toBe('false') - await page.getByRole('button', { name: /^Select model/u }).hover() - await tooltip.waitFor({ state: 'hidden' }) - await page.keyboard.press('Shift') - await info.focus() - await tooltip.waitFor({ state: 'visible' }) - await page.keyboard.press('Escape') - await tooltip.waitFor({ state: 'hidden' }) - expect(await toggle.isVisible()).toBe(true) - await info.click() - await tooltip.waitFor({ state: 'visible' }) - expect(await info.getAttribute('aria-describedby')).toBe(await tooltip.getAttribute('id')) - expect(await toggle.getAttribute('aria-checked')).toBe('false') - await page.keyboard.press('Escape') - await tooltip.waitFor({ state: 'hidden' }) - await page.keyboard.press('Escape') - expect(tripwire.pageErrors).toEqual([]) + const trigger = page.getByRole('button', { name: /^Select model/u }) + await trigger.click() + const menu = page.getByRole('menu') + const summary = menu.getByRole('menuitem', { name: 'Agent teamwork Off', exact: true }) + await summary.waitFor() + // The route-only fixture supplies no reasoning capability, so no range is invented. + expect(await menu.getByRole('slider', { name: 'Effort', exact: true }).count()).toBe(0) + expect(await menu.getByRole('switch').count()).toBe(0) + expect(await page.getByRole('button', { name: 'About agent teamwork', exact: true }).count()).toBe(0) + const rootSnapshot = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) + const original = await menu.elementHandle() + if (original === null) throw new Error('Model menu is missing') + try { + await summary.click() + const toggle = menu.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) + await toggle.waitFor() + expect(await original.evaluate(element => element.isConnected)).toBe(true) + await menu.getByText('Coordinate work and progress across agents with a shared task board for better results on complex tasks, with correspondingly higher token costs.', { exact: true }).waitFor() + expect(await page.getByRole('tooltip').count()).toBe(0) + expect(await toggle.getAttribute('aria-checked')).toBe('false') + const settingsSnapshot = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) + await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'info.expected.md'), + `## Root\n\n${rootSnapshot}\n\n## Team settings\n\n${settingsSnapshot}`, MODE) + await page.keyboard.press('Escape') + await expect.poll(() => summary.evaluate(element => element === document.activeElement)).toBe(true) + expect(await menu.getByRole('switch').count()).toBe(0) + await summary.press('Enter') + await toggle.waitFor() + await page.keyboard.press('Escape') + await summary.waitFor() + expect(await summary.evaluate(element => element === document.activeElement)).toBe(true) + expect(scaffold.ctx.agentTeams.isEnabled(scaffold.ctx.agents.list()[0]!)).toBe(false) + await page.keyboard.press('Escape') + await menu.waitFor({ state: 'hidden' }) + expect(tripwire.pageErrors).toEqual([]) + } finally { + await closeModelMenu(page) + await original.dispose() + } }) - it('toggles from the row label and empty space while keeping the information button independent', async () => { - onTestFailed(() => saveFailureShot(page, 'web-e2e-team-row')) - await page.getByRole('button', { name: /^Select model/u }).click() - const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) - const info = page.getByRole('button', { name: 'About agent teamwork', exact: true }) - const label = page.getByText('Enable agent teamwork', { exact: true }) - const labelBounds = await label.boundingBox() - if (labelBounds === null) throw new Error('Team label is not visible') - const labelPoint = { x: labelBounds.x + labelBounds.width / 2, y: labelBounds.y + labelBounds.height / 2 } - await page.mouse.move(labelPoint.x, labelPoint.y) - expect(await toggle.evaluate((element) => { - const row = element.parentElement! - return getComputedStyle(row).backgroundColor !== 'rgba(0, 0, 0, 0)' - })).toBe(true) - await page.mouse.click(labelPoint.x, labelPoint.y) - await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') - await info.click() - await page.getByRole('tooltip').waitFor({ state: 'visible' }) - expect(await toggle.getAttribute('aria-checked')).toBe('true') - await page.keyboard.press('Escape') - const gap = await toggle.evaluate((element) => { - const control = element.getBoundingClientRect() - const help = element.parentElement!.querySelector('button:not([role="switch"])')!.getBoundingClientRect() - return { x: (help.right + control.left) / 2, y: control.top + control.height / 2 } + it('keeps explanatory text noninteractive and the settings page inside wide and narrow viewports', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-team-settings-page')) + const viewport = page.viewportSize()! + try { + await openTeamSettings(page) + const menu = page.getByRole('menu') + const toggle = menu.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) + const description = menu.getByText('Coordinate work and progress across agents with a shared task board for better results on complex tasks, with correspondingly higher token costs.', { exact: true }) + await description.click() + expect(await menu.isVisible()).toBe(true) + expect(await toggle.getAttribute('aria-checked')).toBe('false') + for (const size of [viewport, { width: 390, height: 700 }]) { + await page.setViewportSize(size) + await expect.poll(() => menu.evaluate((element) => { + const bounds = element.getBoundingClientRect() + return bounds.left >= 12 && bounds.right <= innerWidth - 12 + && bounds.top >= 12 && bounds.bottom <= innerHeight - 12 + && element.scrollWidth <= element.clientWidth + })).toBe(true) + } + await toggle.click() + await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') + await page.keyboard.press('Escape') + await menu.getByRole('menuitem', { name: 'Agent teamwork On', exact: true }).click() + await toggle.click() + await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('false') + expect(await page.getByRole('tooltip').count()).toBe(0) + expect(tripwire.pageErrors).toEqual([]) + } finally { + await closeModelMenu(page) + await page.setViewportSize(viewport) + } + }) + + it('keeps keyboard focus on the Team switch through pending writes and rejects repeated activation', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-team-keyboard-pending')) + const service = scaffold.ctx.agentTeams + const setEnabled = service.setEnabled.bind(service) + const agent = scaffold.ctx.agents.list()[0]! + const initial = service.isEnabled(agent) + onTestFinished(async () => { + await closeModelMenu(page) + await setEnabled(agent, initial) }) - await page.mouse.click(gap.x, gap.y) - await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('false') - expect(await page.getByRole('tooltip').count()).toBe(0) - await page.keyboard.press('Escape') + await openTeamSettings(page) + const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) + for (const enabled of [true, false]) { + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + let inFlight: Promise | undefined + const write = vi.spyOn(service, 'setEnabled').mockImplementation((...args) => { + inFlight = (async () => { + entered.resolve(undefined) + await release.promise + await setEnabled(...args) + })() + return inFlight + }) + try { + await toggle.focus() + await page.keyboard.press('Space') + await entered.promise + await expect.poll(() => toggle.getAttribute('aria-busy')).toBe('true') + expect(await toggle.evaluate(element => (element as HTMLButtonElement).disabled)).toBe(false) + expect(await toggle.getAttribute('aria-disabled')).toBe('true') + expect(await toggle.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Enter') + await page.keyboard.press('Space') + expect(write).toHaveBeenCalledTimes(1) + expect(await toggle.getAttribute('aria-checked')).toBe(String(!enabled)) + release.resolve(undefined) + await expect.poll(() => toggle.getAttribute('aria-checked')).toBe(String(enabled)) + await expect.poll(() => toggle.getAttribute('aria-busy')).toBeNull() + expect(await toggle.getAttribute('aria-disabled')).toBeNull() + expect(await toggle.evaluate(element => element === document.activeElement)).toBe(true) + } finally { + release.resolve(undefined) + try { await inFlight } finally { write.mockRestore() } + } + } expect(tripwire.pageErrors).toEqual([]) }) it('defaults off and saves a Session selection in the model menu', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-team-mode')) expect(await page.locator('[data-subagent-action]').count()).toBe(0) - await page.getByRole('button', { name: /^Select model/u }).click() + await openTeamSettings(page) const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) await toggle.waitFor() expect(await toggle.getAttribute('aria-checked')).toBe('false') await toggle.focus() - await page.keyboard.press('ArrowUp') - expect(await toggle.evaluate(element => element === document.activeElement)).toBe(false) - await page.keyboard.press('ArrowDown') + await page.keyboard.press('Shift+Tab') + expect(await page.getByRole('button', { name: /^Select model/u }).evaluate(element => element === document.activeElement)).toBe(true) + expect(await toggle.count()).toBe(0) + await openTeamSettings(page) expect(await toggle.evaluate(element => element === document.activeElement)).toBe(true) await page.keyboard.press('Space') await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') - await page.keyboard.press('Escape') + await closeModelMenu(page) expect(await page.locator('[data-subagent-action]').count()).toBe(0) const agent = scaffold.ctx.agents.list()[0]! expect(scaffold.ctx.commands.list(agent).some(command => command.name === 'team')).toBe(false) @@ -198,10 +278,10 @@ describe('web e2e: agent teamwork panel', () => { await other.dispose() const beforeReload = tripwire.warnings.length await page.reload({ waitUntil: 'load' }) - await page.getByRole('button', { name: /^Select model/u }).click() + await openTeamSettings(page) expect(await page.locator('[data-subagent-action]').count()).toBe(0) expect(await toggle.getAttribute('aria-checked')).toBe('true') - await page.keyboard.press('Escape') + await closeModelMenu(page) acknowledgeReloadConnectionLoss(tripwire, beforeReload) }, 60_000) @@ -210,11 +290,11 @@ describe('web e2e: agent teamwork panel', () => { const input = page.locator('[data-composer-input]').first() const agent = scaffold.ctx.agents.list()[0]! for (const enabled of [false, true]) { - await page.getByRole('button', { name: /^Select model/u }).click() + await openTeamSettings(page) const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) await toggle.click() await expect.poll(() => toggle.getAttribute('aria-checked')).toBe(String(enabled)) - await page.keyboard.press('Escape') + await closeModelMenu(page) await expect.poll(() => scaffold.ctx.agentTeams.isEnabled(agent)).toBe(enabled) await expect.poll(() => input.textContent()).toBe('') await page.getByRole('button', { name: 'Account menu', exact: true }).focus() @@ -434,22 +514,22 @@ describe('web e2e: agent teamwork panel', () => { }, 60_000) it('hides the board while disabled and restores its tasks when re-enabled', async () => { - await page.getByRole('button', { name: /^Select model/u }).click() + await openTeamSettings(page) const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) await toggle.click() await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('false') expect(await page.locator('[data-subagent-action]').count()).toBe(1) - await page.keyboard.press('Escape') + await closeModelMenu(page) await page.locator('[data-subagent-action]').getByRole('button', { name: '1 subagent', exact: true }).click() await page.getByRole('treeitem', { name: /Researcher/u }).waitFor() expect(await page.locator('[data-team-panel]').count()).toBe(0) expect(await page.locator('[data-subagent-panel]').evaluate(element => element.getBoundingClientRect().width)).toBe(360) expect(await page.locator('[data-subagent-section-header]').count()).toBe(0) await page.keyboard.press('Escape') - await page.getByRole('button', { name: /^Select model/u }).click() + await openTeamSettings(page) await toggle.click() await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') - await page.keyboard.press('Escape') + await closeModelMenu(page) await page.locator('[data-subagent-action]').getByRole('button', { name: /subagents?$/u }).click() await page.locator('[data-subagent-panel]').getByText('Agent task', { exact: true }).waitFor() await page.keyboard.press('Escape') @@ -784,14 +864,15 @@ describe('web e2e: agent teamwork panel', () => { agent.session.append('request/header', { header: { config: selection }, reason: 'initial' }) await scaffold.ctx.sessions.flush(agent.session) const openConfirmation = async (): Promise => { - await page.getByRole('button', { name: /^Select model/u }).click() + await openTeamSettings(page) await page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }).click() await page.getByRole('dialog', { name: 'Disable agent teamwork?', exact: true }).waitFor() } await openConfirmation() const dialog = page.getByRole('dialog', { name: 'Disable agent teamwork?', exact: true }) await assertWarningDialogLayout(dialog) - expect(await page.getByRole('menu', { name: 'Model and reasoning effort', exact: true }).count()).toBe(0) + expect(await page.getByRole('menu', { name: 'Agent teamwork', exact: true }).count()).toBe(0) + expect(await page.getByRole('button', { name: /^Select model/u }).getAttribute('aria-expanded')).toBe('false') expect(await dialog.getByRole('checkbox').count()).toBe(0) expect(scaffold.ctx.agentTeams.isEnabled(agent)).toBe(true) await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'disable-confirmation.expected.md'), @@ -810,11 +891,11 @@ describe('web e2e: agent teamwork panel', () => { await dialog.waitFor({ state: 'hidden' }) await expect.poll(() => page.getByRole('button', { name: /^Select model/u }).evaluate(element => element === document.activeElement)).toBe(true) await expect.poll(() => scaffold.ctx.agentTeams.isEnabled(agent)).toBe(false) - await page.getByRole('button', { name: /^Select model/u }).click() + await openTeamSettings(page) await page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }).click() await expect.poll(() => scaffold.ctx.agentTeams.isEnabled(agent)).toBe(true) expect(await dialog.count()).toBe(0) - await page.keyboard.press('Escape') + await closeModelMenu(page) expect(agent.session.ownEvents().filter(event => event.type === 'command/run' || event.type === 'command/done')).toEqual([]) expect(tripwire.pageErrors).toEqual([]) }) @@ -891,14 +972,14 @@ it.each(RECEIPT_LOCALES)('toggles teamwork in $language without command records await expect.poll(captureLayout).toEqual(recordedLayout) } for (const enabled of [true, false]) { - await page.getByRole('button', { name: locale.modelButton }).click() + await openTeamSettings(page, locale.code === 'zh') const toggle = page.getByRole('switch', { name: locale.toggle, exact: true }) await toggle.click() await expect.poll(() => toggle.getAttribute('aria-checked')).toBe(String(enabled)) await expect.poll(() => scaffold.ctx.agentTeams.isEnabled(agent)).toBe(enabled) expect(scaffold.ctx.commands.list(agent).some(command => command.name === 'team')).toBe(false) expect(commandEvents()).toEqual([]) - await page.keyboard.press('Escape') + await closeModelMenu(page) await assertChatUnchanged() } await scaffold.ctx.sessions.flush(agent.session) @@ -1003,10 +1084,11 @@ it('uses the Chinese collaboration name in the switch and disable confirmation', if (selection === undefined) throw new Error('Chinese Team fixture has no model') agent.session.append('request/header', { header: { config: selection }, reason: 'initial' }) await scaffold.ctx.sessions.flush(agent.session) - await page.getByRole('button', { name: /^选择模型/u }).click() + await openTeamSettings(page, true) const toggle = page.getByRole('switch', { name: '启用智能体团队协作', exact: true }) await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') - await page.getByRole('button', { name: '关于智能体团队协作', exact: true }).waitFor() + await page.getByText('通过共享任务板协调多个智能体的分工与进度,复杂任务表现更佳,token 开销也相应更高。', { exact: true }).waitFor() + expect(await page.getByRole('tooltip').count()).toBe(0) expect(await toggle.evaluate(element => element.parentElement!.scrollWidth <= element.parentElement!.clientWidth)).toBe(true) const menu = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) await toggle.click() diff --git a/apps/web/tests/declared-reasoning.e2e.ts b/apps/web/tests/declared-reasoning.e2e.ts index 27619f0bf1..95b6244e3b 100644 --- a/apps/web/tests/declared-reasoning.e2e.ts +++ b/apps/web/tests/declared-reasoning.e2e.ts @@ -1,12 +1,12 @@ // Web e2e scenario: a hand-declared model's `reasoningEfforts` reaches the -// composer's effort pane — the levels a settings profile declares are exactly +// composer's inline effort slider — the levels a settings profile declares are exactly // what the picker offers, and picking one records it with the Agent default. // Zero model calls: declaring, describing, and switching are settings/llm // traffic only, so there is no fixture and a stray stream would fail loud. import { readFile } from 'node:fs/promises' import { fileURLToPath } from 'node:url' import { join } from 'node:path' -import type { Browser, Page, Request } from 'playwright' +import type { Browser, Locator, Page, Request } from 'playwright' import { chromium, webkit } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed, onTestFinished } from 'vitest' import { @@ -49,7 +49,9 @@ describe.skipIf(MODE === 'record').each([ { id: 'acme-lite', name: 'Acme Lite' }, ].map(model => ({ ...model, - reasoningEfforts: { off: null, high: 'high', max: 'ultra' }, + reasoningEfforts: model.id === 'acme-lite' + ? { low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh', max: 'max' } + : { off: null, high: 'high', max: 'ultra' }, })), }, }, @@ -70,68 +72,119 @@ describe.skipIf(MODE === 'record').each([ } }) - it('offers exactly the declared levels and records the picked one', async () => { + it('uses Tab only for focus while Enter and Space open model and Team pages', async () => { + onTestFailed(() => saveFailureShot(page, `web-e2e-model-tab-${engine.name()}`)) + let selections = 0 + const countSelection = (request: Request): void => { + if (new URL(request.url()).pathname.endsWith('/session/selectModel')) selections++ + } + page.on('request', countSelection) + onTestFinished(() => { page.off('request', countSelection) }) + const previous = scaffold.ctx.agentDefaultModel.currentSelection() + const trigger = page.getByRole('button', { name: /^选择模型/ }) + const rootModel = page.locator('[data-model-menu-root] > button[role="menuitem"]') + const slider = page.getByRole('slider', { name: '推理等级', exact: true }) + const team = page.locator('[data-model-menu-page="agent-team"]') + const focused = async (locator: Locator): Promise => { + await expect.poll(() => locator.evaluate(element => element === document.activeElement)).toBe(true) + } + await trigger.click() + await page.keyboard.press('Tab'); await focused(rootModel) + expect(await page.getByRole('menuitemradio').count()).toBe(0) + await page.keyboard.press('Tab'); await focused(slider) + await page.keyboard.press('Tab'); await focused(team) + expect(await page.getByRole('switch').count()).toBe(0) + await page.keyboard.press('Shift+Tab'); await focused(slider) + await page.keyboard.press('Shift+Tab'); await focused(rootModel) + await page.keyboard.press('Enter') + const search = page.getByRole('searchbox', { name: '搜索模型…', exact: true }) + await search.waitFor(); await focused(search) + await page.mouse.move(0, 0) + await page.keyboard.press('Escape'); await focused(rootModel) + expect(await rootModel.evaluate(element => getComputedStyle(element).backgroundColor)).toBe('rgba(0, 0, 0, 0)') + await page.keyboard.press('Space'); await focused(search) + await page.keyboard.press('Tab') + await focused(page.locator('[role="menuitemradio"][tabindex="0"]')) + expect(selections).toBe(0) + expect(scaffold.ctx.agentDefaultModel.currentSelection()).toEqual(previous) + await page.keyboard.press('Shift+Tab'); await focused(search) + await page.keyboard.press('Shift+Tab'); await focused(trigger) + expect(await search.count()).toBe(0) + await page.keyboard.press('Enter') + await page.keyboard.press('Tab'); await focused(rootModel) + await page.keyboard.press('Space'); await search.waitFor() + await page.keyboard.press('Tab') + await focused(page.locator('[role="menuitemradio"][aria-checked="true"]')) + await page.keyboard.press('Space'); await focused(rootModel) + await page.keyboard.press('Tab'); await focused(slider) + await page.keyboard.press('Tab'); await focused(team) + await page.keyboard.press('Space') + const toggle = page.getByRole('switch', { name: '启用智能体团队协作', exact: true }) + await toggle.waitFor(); await focused(toggle) + const checked = await toggle.getAttribute('aria-checked') + await page.keyboard.press('Shift+Tab'); await focused(trigger) + expect(await toggle.count()).toBe(0) + await page.keyboard.press('Enter') + await team.click(); await focused(toggle) + expect(await toggle.getAttribute('aria-checked')).toBe(checked) + expect(await page.getByRole('button', { name: '返回', exact: true }).count()).toBe(0) + await page.keyboard.press('Escape'); await focused(team) + await page.keyboard.press('Tab') + await page.locator('[data-model-menu-root]').waitFor({ state: 'detached' }) + expect(await trigger.evaluate(element => element === document.activeElement)).toBe(false) + expect(selections).toBe(0) + expect(scaffold.ctx.agentDefaultModel.currentSelection()).toEqual(previous) + expect(tripwire.pageErrors).toEqual([]) + }, 60_000) + + it('offers exactly the declared levels in the root slider and records one keyboard selection', async () => { onTestFailed(() => saveFailureShot(page, `web-e2e-declared-reasoning-${engine.name()}`)) const trigger = page.getByRole('button', { name: /^选择模型/ }) await trigger.waitFor({ timeout: 15_000 }) + onTestFinished(async () => { + if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() + }) await trigger.click() - await page.getByRole('menuitem', { name: /推理等级/ }).click() - - // Declared levels, nothing else: the provider-default entry (the route - // configures no `reasoning`), then Off/High/Max — minimal, low, medium, - // and xhigh were not declared and must not be offered. - const levels = page.getByRole('menuitemradio') - await expect.poll(async () => levels.allTextContents(), { timeout: 10_000 }) - .toEqual(['Default', 'Off', 'High', 'Max']) + const slider = page.getByRole('slider', { name: '推理等级', exact: true }) + const levels = page.getByRole('group', { name: '推理等级', exact: true }).getByRole('button') + expect(await levels.count()).toBe(0) + expect(await slider.getAttribute('min')).toBe('0') + expect(await slider.getAttribute('max')).toBe('3') + expect(await slider.getAttribute('aria-valuetext')).toBe('Default') + const tag = page.getByRole('group', { name: '推理等级', exact: true }).getByText('Default', { exact: true }) + expect(await tag.evaluate(element => ({ + cursor: getComputedStyle(element).cursor, + userSelect: getComputedStyle(element).getPropertyValue(CSS.supports('user-select', 'none') ? 'user-select' : '-webkit-user-select'), + tabIndex: element.tabIndex, + }))).toEqual({ cursor: 'default', userSelect: 'none', tabIndex: -1 }) + expect(await page.getByRole('menuitem', { name: /推理等级/ }).count()).toBe(0) const snapshot = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE) - - // 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') - await expect.poll( - () => levels.nth(1).evaluate(element => element === document.activeElement), - { timeout: 10_000 }, - ).toBe(true) - await page.keyboard.press('ArrowDown') - 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. - await page.keyboard.press('Tab') - await expect.poll(() => levels.count(), { timeout: 10_000 }).toBe(0) + const previous = scaffold.ctx.agentDefaultModel.currentSelection() + await slider.focus() + try { + await page.keyboard.down('ArrowRight') + await expect.poll(() => slider.inputValue()).toBe('1') + await page.keyboard.down('ArrowRight') + await expect.poll(() => slider.inputValue()).toBe('2') + expect(scaffold.ctx.agentDefaultModel.currentSelection()).toEqual(previous) + } finally { + await page.keyboard.up('ArrowRight') + } + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) await expect.poll( async () => readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), '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 expect.poll(() => trigger.getAttribute('aria-label')).toBe('选择模型,当前 Acme Think,推理等级 High') + expect(await slider.getAttribute('aria-valuetext')).toBe('High') + await slider.focus() await page.keyboard.press('Shift+Tab') - await expect.poll( - () => page.getByRole('menuitem', { name: /推理等级/ }) - .evaluate(element => element === document.activeElement), - { timeout: 10_000 }, - ).toBe(true) + await expect.poll(() => page.getByRole('menuitem', { name: /^模型/ }) + .evaluate(element => element === document.activeElement)).toBe(true) await page.keyboard.press('Shift+Tab') - await expect.poll(() => page.getByRole('menu').count(), { timeout: 10_000 }).toBe(0) + await expect.poll(() => page.getByRole('menu').count()).toBe(0) expect(tripwire.pageErrors).toEqual([]) }, 60_000) @@ -139,7 +192,7 @@ describe.skipIf(MODE === 'record').each([ onTestFailed(() => saveFailureShot(page, `web-e2e-model-trigger-${engine.name()}`)) const trigger = page.getByRole('button', { name: /^选择模型/ }) const menu = page.getByRole('menu') - for (const pane of ['root', 'model', 'effort']) { + for (const pane of ['root', 'model', 'slider']) { await page.locator('[data-composer-input][contenteditable="true"]').focus() await trigger.click() await expect.poll(() => trigger.evaluate(element => element === document.activeElement)).toBe(true) @@ -148,10 +201,11 @@ describe.skipIf(MODE === 'record').each([ await expect.poll(() => page.getByRole('menuitem', { name: /^模型/ }) .evaluate(element => element === document.activeElement)).toBe(true) } else { - await page.getByRole('menuitem', { name: pane === 'model' ? /^模型/ : /推理等级/ }).click() + if (pane === 'model') await page.getByRole('menuitem', { name: /^模型/ }).click() const focused = pane === 'model' ? page.getByRole('searchbox', { name: '搜索模型…' }) - : page.locator('[role="menuitemradio"][aria-checked="true"]') + : page.getByRole('slider', { name: '推理等级', exact: true }) + if (pane === 'slider') await focused.focus() await expect.poll(() => focused.evaluate(element => element === element.ownerDocument.activeElement)).toBe(true) } await trigger.click() @@ -171,6 +225,9 @@ describe.skipIf(MODE === 'record').each([ onTestFinished(() => { page.off('request', countSelection) }) const trigger = page.getByRole('button', { name: /^选择模型/ }) const menu = page.getByRole('menu') + onTestFinished(async () => { + if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() + }) await trigger.click() await page.getByRole('menuitem', { name: /^模型/ }).click() const current = page.getByRole('menuitemradio', { name: 'Acme Think', exact: true }) @@ -203,15 +260,28 @@ describe.skipIf(MODE === 'record').each([ await trigger.click() await page.getByRole('menuitem', { name: /^模型/ }).click() await target.getByText('Acme Swift', { exact: true }).click() - await menu.waitFor({ state: 'detached' }) + await page.locator('[data-model-menu-root]').waitFor() expect(selections).toBe(1) await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().model, { timeout: 10_000 }) .toBe('acme-swift') - await trigger.click() - await page.getByRole('menuitem', { name: /推理等级/ }).click() - await page.getByRole('menuitemradio', { name: 'Max', exact: true }).click() - await menu.waitFor({ state: 'detached' }) + const rootModel = page.getByRole('menuitem', { name: /^模型/ }) + await expect.poll(() => rootModel.evaluate(element => element === document.activeElement)).toBe(true) + expect(await rootModel.evaluate(element => getComputedStyle(element).backgroundColor)).toBe('rgba(0, 0, 0, 0)') + await rootModel.hover() + await expect.poll(() => rootModel.evaluate(element => getComputedStyle(element).backgroundColor)).not.toBe('rgba(0, 0, 0, 0)') + await page.mouse.move(0, 0) + await page.keyboard.press('Tab') + const slider = page.getByRole('slider', { name: '推理等级', exact: true }) + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Shift+Tab') + expect(await rootModel.evaluate(element => element === document.activeElement)).toBe(true) + expect(await rootModel.evaluate(element => getComputedStyle(element).backgroundColor)).not.toBe('rgba(0, 0, 0, 0)') + expect(selections).toBe(1) + const rangeBounds = await slider.boundingBox() + if (rangeBounds === null) throw new Error('Reasoning slider is not visible') + await page.mouse.click(rangeBounds.x + rangeBounds.width - 8, rangeBounds.y + rangeBounds.height / 2) + await expect.poll(() => slider.getAttribute('aria-valuetext')).toBe('Max') expect(selections).toBe(2) await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort, { timeout: 10_000 }) .toBe('max') @@ -228,7 +298,6 @@ describe.skipIf(MODE === 'record').each([ }, }) }, { times: 1 }) - await trigger.click() await page.getByRole('menuitem', { name: /^模型/ }).click() await expect.poll(() => search.evaluate(element => element === element.ownerDocument.activeElement)).toBe(true) expect(await search.getAttribute('aria-activedescendant')).toBe(await target.getAttribute('id')) @@ -236,12 +305,15 @@ describe.skipIf(MODE === 'record').each([ await page.getByRole('alert').waitFor() expect(selections).toBe(3) await compareOrRefreshGolden(POINTER_EXPECTED, - await captureStableAria(page, '[role="group"][aria-label="模型与推理等级"]', scaffold.workspaceCwd), MODE) - await expect.poll(() => trigger.evaluate(element => element === document.activeElement)).toBe(true) - await page.keyboard.press('Tab') + await captureStableAria(page, '[role="group"][aria-label="模型"]', scaffold.workspaceCwd), MODE) + const focusedRow = page.locator('[role="menuitemradio"][tabindex="0"]') + await expect.poll(() => focusedRow.evaluate(element => element === document.activeElement)).toBe(true) + expect(await target.getAttribute('aria-checked')).toBe('true') + expect(scaffold.ctx.agentDefaultModel.currentSelection().model).toBe('acme-swift') + await page.keyboard.press('Shift+Tab') await expect.poll(() => search.evaluate(element => element === element.ownerDocument.activeElement)).toBe(true) - expect(await search.getAttribute('aria-activedescendant')).toBe(await target.getAttribute('id')) - await search.press('ArrowUp') + await search.fill('Acme Think') + await search.press('ArrowDown') expect(await search.getAttribute('aria-activedescendant')).toBe(await current.getAttribute('id')) expect(await search.evaluate(element => element === element.ownerDocument.activeElement)).toBe(true) await page.keyboard.press('Escape') @@ -250,7 +322,11 @@ describe.skipIf(MODE === 'record').each([ await trigger.click() await page.getByRole('menuitem', { name: /^模型/ }).click() - await page.locator('[data-composer-input][contenteditable="true"]').focus() + await expect.poll(() => search.evaluate(element => element === document.activeElement)).toBe(true) + const composer = page.locator('[data-composer-input][contenteditable="true"]') + // Native focus supplies relatedTarget; Playwright's contentEditable focus first blurs to null. + await composer.evaluate((element) => { element.focus() }) + await expect.poll(() => composer.evaluate(element => element === document.activeElement)).toBe(true) await menu.waitFor({ state: 'detached' }) await trigger.click() await page.mouse.click(0, 0) @@ -258,6 +334,75 @@ describe.skipIf(MODE === 'record').each([ expect(tripwire.pageErrors).toEqual([]) }) + it('shows six stops including Default and commits only after releasing a drag outside the range', async () => { + onTestFailed(() => saveFailureShot(page, `web-e2e-six-effort-drag-${engine.name()}`)) + const trigger = page.getByRole('button', { name: /^选择模型/ }) + const viewport = page.viewportSize()! + await trigger.click() + await page.getByRole('menuitem', { name: /^模型/ }).click() + await page.getByRole('menuitemradio', { name: 'Acme Lite', exact: true }).click() + await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().model).toBe('acme-lite') + let selections = 0 + const countSelection = (request: Request): void => { + if (new URL(request.url()).pathname.endsWith('/session/selectModel')) selections++ + } + page.on('request', countSelection) + onTestFinished(() => { page.off('request', countSelection) }) + try { + await page.setViewportSize({ width: 390, height: 700 }) + const menu = page.getByRole('menu', { name: '模型与推理等级', exact: true }) + const group = menu.getByRole('group', { name: '推理等级', exact: true }) + const slider = group.getByRole('slider', { name: '推理等级', exact: true }) + expect(await group.getByRole('button').count()).toBe(0) + expect(await slider.getAttribute('aria-valuetext')).toBe('Default') + expect(await slider.getAttribute('max')).toBe('5') + await expect.poll(() => menu.evaluate((element) => { + const rect = element.getBoundingClientRect() + return rect.left >= 12 && rect.right <= innerWidth - 12 && rect.top >= 12 && rect.bottom <= innerHeight - 12 + && element.scrollWidth <= element.clientWidth + })).toBe(true) + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + await slider.hover() + const bounds = await slider.boundingBox() + if (bounds === null) throw new Error('Reasoning slider is not visible') + const y = bounds.y + bounds.height / 2 + await page.mouse.move(bounds.x + 8, y) + await page.mouse.down() + try { + await page.mouse.move(bounds.x + bounds.width * .4, y, { steps: 4 }) + await page.mouse.move(bounds.x + bounds.width * .6, y, { steps: 4 }) + await page.mouse.move(bounds.x + bounds.width - 8, y, { steps: 4 }) + await page.mouse.move(bounds.x + bounds.width + 24, y, { steps: 4 }) + expect(await page.evaluate(({ x, y }) => document.elementFromPoint(x, y)?.matches('input[type="range"]'), + { x: bounds.x + bounds.width + 24, y })).not.toBe(true) + expect(selections).toBe(0) + expect(await menu.isVisible()).toBe(true) + await expect.poll(() => slider.evaluate(input => ({ + value: (input as HTMLInputElement).value, + label: input.getAttribute('aria-valuetext'), + busy: input.getAttribute('aria-busy'), + disabled: (input as HTMLInputElement).disabled, + }))).toEqual({ value: '5', label: 'Max', busy: 'false', disabled: false }) + } catch (error) { + await page.screenshot({ path: fileURLToPath(new URL( + `../../../.artifacts/model-picker-master-sync/drag-${engine.name()}-regression.png`, import.meta.url, + )) }) + throw error + } finally { + await page.mouse.up() + } + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + expect(await menu.isVisible()).toBe(true) + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + expect(selections).toBe(1) + await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBe('max') + expect(tripwire.pageErrors).toEqual([]) + } finally { + await page.keyboard.press('Escape') + await page.setViewportSize(viewport) + } + }) + it('keeps its snapshot inventory closed', async () => { await assertFixtureInventory(SNAPSHOT_DIR, ['ui.expected.md', 'pointer-menu.expected.md']) }) diff --git a/apps/web/tests/deepseek-messages-settings.e2e.ts b/apps/web/tests/deepseek-messages-settings.e2e.ts index 6033c8f06f..a842669c01 100644 --- a/apps/web/tests/deepseek-messages-settings.e2e.ts +++ b/apps/web/tests/deepseek-messages-settings.e2e.ts @@ -120,13 +120,18 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett await page.getByRole('menuitem', { name: /模型/ }).click() await page.getByRole('menuitemradio', { name: 'Messages Flash', exact: true }).waitFor() await compareOrRefreshGolden(join(EXPECTED, 'picker.expected.md'), - await captureStableAria(page, '[role="group"][aria-label="模型与推理等级"]', scaffold.workspaceCwd), webSnapshotMode()) + await captureStableAria(page, '[role="group"][aria-label="模型"]', scaffold.workspaceCwd), webSnapshotMode()) await page.keyboard.press('Escape') - await page.getByRole('menuitem', { name: /推理等级/ }).click() - const effortWeights = await page.getByRole('menuitemradio').evaluateAll(rows => rows.map(row => - getComputedStyle(row.querySelector('span span')!).fontWeight, - )) - expect(new Set(effortWeights)).toEqual(new Set(['400'])) + const effort = page.getByRole('group', { name: '推理等级', exact: true }) + await effort.getByRole('slider', { name: '推理等级', exact: true }).waitFor() + expect(await effort.getByRole('button').count()).toBe(0) + const slider = effort.getByRole('slider') + expect(await slider.getAttribute('min')).toBe('0') + expect(await slider.getAttribute('max')).toBe('3') + expect(await slider.getAttribute('aria-valuetext')).toBe('High') + const tag = effort.getByText('High', { exact: true }) + expect(await tag.evaluate(element => getComputedStyle(element).fontWeight)).toBe('500') + expect(await tag.evaluate(element => element.tabIndex)).toBe(-1) expect(tripwire.pageErrors).toEqual([]) }, 60_000) diff --git a/apps/web/tests/default-model.e2e.ts b/apps/web/tests/default-model.e2e.ts index afd89b3c77..78c45f1bb0 100644 --- a/apps/web/tests/default-model.e2e.ts +++ b/apps/web/tests/default-model.e2e.ts @@ -116,20 +116,23 @@ describe('web e2e: the composer model switch is the default for later sessions', JSON.stringify(await readLabels(menu), null, 2), webSnapshotMode(), ) + await page.keyboard.press('Escape') + await expect.poll(() => cell.evaluate(element => element === document.activeElement)).toBe(true) + expect(await page.getByRole('menuitemradio').count()).toBe(0) } finally { await page.keyboard.press('Escape') await page.keyboard.press('Escape') } }) - it.each(['root', 'model'])('reanchors the %s menu when a label grows and shrinks without a window resize', async (pane) => { + it.each(['root', 'model'])('keeps the %s menu aligned as a label grows and shrinks without a window resize', async (pane) => { const viewport = page.viewportSize()! const trigger = page.getByRole('button', { name: /^选择模型/ }) try { await page.setViewportSize({ width: 390, height: 844 }) await trigger.click() if (pane === 'model') await page.getByRole('menuitem', { name: /^模型/ }).click() - const surface = page.getByRole(pane === 'model' ? 'group' : 'menu', { name: '模型与推理等级', exact: true }) + const surface = page.getByRole(pane === 'model' ? 'group' : 'menu', { name: pane === 'model' ? '模型' : '模型与推理等级', exact: true }) const label = surface.locator('[data-provider-id="origin-gateway"][data-model-id="origin-large"]') await label.waitFor() const original = await surface.boundingBox() @@ -141,7 +144,9 @@ describe('web e2e: the composer model switch is the default for later sessions', badge.textContent = ' — Provider identification badge with a long channel name' node.appendChild(badge) }) - await expect.poll(async () => (await surface.boundingBox())!.width).toBeGreaterThan(original!.width + 50) + expect(original!.width).toBe(260) + await expect.poll(async () => (await surface.boundingBox())!.width).toBeCloseTo(original!.width) + expect(await surface.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) await expect.poll(async () => { const box = (await surface.boundingBox())! return box.x >= 12 && box.x + box.width <= 378 @@ -272,6 +277,10 @@ describe('web e2e: the composer model switch is the default for later sessions', await expect.poll(() => model.evaluate(element => document.activeElement === element)).toBe(true) await observeFocus('Enter model pane') await devicePage.keyboard.press('ArrowDown') + const next = devicePage.getByRole('menuitemradio', { name: 'Acme Large', exact: true }) + await expect.poll(() => next.evaluate(element => document.activeElement === element)).toBe(true) + expect(await devicePage.locator('[role="menuitemradio"][tabindex="0"]').count()).toBe(1) + await devicePage.keyboard.press('Shift+Tab') const search = devicePage.getByRole('searchbox', { name: '搜索模型…' }) expect(await search.evaluate(input => getComputedStyle(input).fontSize)).toBe('16px') await expect.poll(() => search.evaluate(element => document.activeElement === element)).toBe(true) @@ -320,7 +329,7 @@ describe('web e2e: the composer model switch is the default for later sessions', try { await page.getByRole('button', { name: /^选择模型/ }).click() await page.getByRole('menuitem', { name: /^模型/ }).click() - const menu = page.getByRole('group', { name: '模型与推理等级', exact: true }) + const menu = page.getByRole('group', { name: '模型', exact: true }) const menuSearch = page.getByRole('searchbox', { name: '搜索模型…' }) const order = await readGroups(menu, 'menuitemradio') const sticky = await checkSticky(menu, menu.getByRole('menu', { name: '模型', exact: true })) @@ -368,8 +377,11 @@ describe('web e2e: the composer model switch is the default for later sessions', for (let index = 0; index < 4; index++) await page.keyboard.press('ArrowDown') expect(await page.evaluate(() => document.activeElement?.id)).toBe(currentId) await page.keyboard.press('Enter') - await expect.poll(() => trigger.evaluate(node => node === node.ownerDocument.activeElement)).toBe(true) - expect(await trigger.evaluate(node => getComputedStyle(node).boxShadow)).toBe('none') + await expect.poll(() => page.getByRole('menuitem', { name: /^模型/ }) + .evaluate(node => node === node.ownerDocument.activeElement)).toBe(true) + expect(await trigger.getAttribute('aria-expanded')).toBe('true') + await page.keyboard.press('Escape') + await expect.poll(() => trigger.getAttribute('aria-expanded')).toBe('false') await page.getByRole('button', { name: '添加文件或调用指令', exact: true }).click() await page.getByRole('option', { name: /^模型/ }).click() const commandSearch = page.getByRole('textbox', { name: '筛选选项', exact: true }) @@ -398,11 +410,12 @@ describe('web e2e: the composer model switch is the default for later sessions', platform: document.documentElement.getAttribute('data-platform'), theme: document.body.getAttribute('data-ds-dark-theme'), })) - const surface = page.getByRole('group', { name: '模型与推理等级', exact: true }) + const surface = page.getByRole('group', { name: '模型', exact: true }) const trigger = page.getByRole('button', { name: /^选择模型/ }) const search = page.getByRole('searchbox', { name: '搜索模型…' }) try { - await page.setViewportSize({ width: 1680, height: 220 }) + // Keep multiple provider groups scrollable beneath the search field. + await page.setViewportSize({ width: 1680, height: 280 }) await trigger.click() await page.getByRole('menuitem', { name: /模型/ }).click() const scroller = page.getByRole('menu', { name: '模型', exact: true }) @@ -442,6 +455,7 @@ describe('web e2e: the composer model switch is the default for later sessions', await expect.poll(readPinned).toEqual([true, false, false]) await search.fill('Origin Large') await expect.poll(() => headings.count()).toBe(1) + await expect.poll(() => scroller.evaluate(element => element.scrollHeight <= element.clientHeight)).toBe(true) await expect.poll(readPinned).toEqual([false]) await page.getByRole('button', { name: '清除搜索', exact: true }).click() await expect.poll(readPinned).toEqual([false, false, false]) @@ -534,7 +548,7 @@ describe('web e2e: the composer model switch is the default for later sessions', getComputedStyle(row.querySelector('span span')!).fontWeight, )) expect(new Set(modelWeights)).toEqual(new Set(['400'])) - const headingPalettes = await page.getByRole('group', { name: '模型与推理等级', exact: true }).evaluate((menu) => { + const headingPalettes = await page.getByRole('group', { name: '模型', exact: true }).evaluate((menu) => { const html = menu.ownerDocument.documentElement const body = menu.ownerDocument.body const previousPlatform = html.getAttribute('data-platform') @@ -582,7 +596,7 @@ describe('web e2e: the composer model switch is the default for later sessions', expect(await page.getByRole('group', { name: 'Origin Gateway', exact: true }).count()).toBe(0) await compareOrRefreshGolden( fileURLToPath(new URL('./expected/default-model/search.expected.md', import.meta.url)), - await captureStableAria(page, '[role="group"][aria-label="模型与推理等级"]', scaffold.workspaceCwd), + await captureStableAria(page, '[role="group"][aria-label="模型"]', scaffold.workspaceCwd), webSnapshotMode(), ) const entered = Promise.withResolvers() @@ -600,9 +614,11 @@ describe('web e2e: the composer model switch is the default for later sessions', await page.keyboard.press('Enter') await expect.poll(() => trigger.getAttribute('aria-busy')).toBe('false') await expect.poll(() => trigger.textContent()).toContain('Acme Large') - await expect.poll(() => trigger.evaluate(element => element === element.ownerDocument.activeElement)).toBe(true) - expect(await trigger.evaluate(element => getComputedStyle(element).boxShadow)).toBe('none') + await expect.poll(() => modelCell.evaluate(element => element === element.ownerDocument.activeElement)).toBe(true) + expect(await trigger.getAttribute('aria-expanded')).toBe('true') expect(scaffold.ctx.agentDefaultModel.currentSelection()).toEqual({ provider: START_ROUTE, model: START_MODEL }) + await page.keyboard.press('Escape') + await expect.poll(() => trigger.getAttribute('aria-expanded')).toBe('false') const aria = await captureStableAria(page, '[data-composer-card]', scaffold.workspaceCwd) await compareOrRefreshGolden(fileURLToPath(new URL('./expected/default-model/background-save.expected.md', import.meta.url)), aria, webSnapshotMode()) } finally { diff --git a/apps/web/tests/expected/declared-reasoning/pointer-menu.expected.md b/apps/web/tests/expected/declared-reasoning/pointer-menu.expected.md index 2a5271a974..007884ec01 100644 --- a/apps/web/tests/expected/declared-reasoning/pointer-menu.expected.md +++ b/apps/web/tests/expected/declared-reasoning/pointer-menu.expected.md @@ -1,4 +1,4 @@ -- group "模型与推理等级": +- group "模型": - searchbox "搜索模型…" - menu "模型": - group "DeepSeek": diff --git a/apps/web/tests/expected/declared-reasoning/ui.expected.md b/apps/web/tests/expected/declared-reasoning/ui.expected.md index 2b18a73716..a56dedf7d1 100644 --- a/apps/web/tests/expected/declared-reasoning/ui.expected.md +++ b/apps/web/tests/expected/declared-reasoning/ui.expected.md @@ -1,5 +1,6 @@ - menu "模型与推理等级": - - menuitemradio "Default" [checked] - - menuitemradio "Off" - - menuitemradio "High" - - menuitemradio "Max" + - menuitem "模型 Acme Think" + - group "推理等级": + - text: Default + - slider "推理等级": "0" + - menuitem "智能体团队协作 关" 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 f256339fcd..5b8cc4753a 100644 --- a/apps/web/tests/expected/deepseek-messages-settings/picker.expected.md +++ b/apps/web/tests/expected/deepseek-messages-settings/picker.expected.md @@ -1,4 +1,4 @@ -- group "模型与推理等级": +- group "模型": - menu "模型": - group "DeepSeek": - text: DeepSeek diff --git a/apps/web/tests/expected/default-model/search.expected.md b/apps/web/tests/expected/default-model/search.expected.md index 9b2d48e3c8..2379835f56 100644 --- a/apps/web/tests/expected/default-model/search.expected.md +++ b/apps/web/tests/expected/default-model/search.expected.md @@ -1,4 +1,4 @@ -- group "模型与推理等级": +- group "模型": - searchbox "搜索模型…": ACMLG - button "清除搜索" - menu "模型": diff --git a/apps/web/tests/model-menu-observer.e2e.ts b/apps/web/tests/model-menu-observer.e2e.ts index 7bd5720bc5..d0a1cab304 100644 --- a/apps/web/tests/model-menu-observer.e2e.ts +++ b/apps/web/tests/model-menu-observer.e2e.ts @@ -150,7 +150,7 @@ describe.skipIf(webSnapshotMode() === 'record').each([ for (const entry of ['button', 'command'] as const) { const composer = page.locator('[data-composer-input]').first() const surface = entry === 'button' - ? page.getByRole('group', { name: '模型与推理等级', exact: true }) + ? page.getByRole('group', { name: '模型', exact: true }) : page.locator('[aria-label="/model 选项"]') const viewport = entry === 'button' ? surface.getByRole('menu', { name: '模型', exact: true }) @@ -296,7 +296,7 @@ describe.skipIf(webSnapshotMode() === 'record').each([ await page.setViewportSize({ width: 402, height: 874 }) await page.getByRole('button', { name: /^选择模型/ }).click() await page.getByRole('menuitem', { name: /^模型/ }).click() - const panel = page.getByRole('group', { name: '模型与推理等级', exact: true }) + const panel = page.getByRole('group', { name: '模型', exact: true }) for (const height of [874, 500]) { await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: 1 }) await page.setViewportSize({ width: 402, height }) @@ -398,66 +398,67 @@ describe.skipIf(webSnapshotMode() === 'record').each([ } }) - it.runIf(engine === chromium)('keeps reasoning efforts selectable after zooming with and without list overflow', async () => { + it.runIf(engine === chromium)('keeps reasoning efforts selectable after zooming with and without root overflow', async () => { const cdp = await page.context().newCDPSession(page) try { - for (const { height, scrolls } of [{ height: 500, scrolls: false }, { height: 350, scrolls: true }]) { + for (const { height, scrolls } of [{ height: 500, scrolls: false }, { height: 220, scrolls: true }]) { await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: 1 }) await page.setViewportSize({ width: 402, height }) await page.getByRole('button', { name: /^选择模型/ }).click() - await page.getByRole('menuitem', { name: /^推理等级/ }).click() const menu = page.getByRole('menu', { name: '模型与推理等级', exact: true }) - await menu.getByRole('menuitemradio').first().click() + const slider = menu.getByRole('slider', { name: '推理等级', exact: true }) + await slider.press('Home') await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBeUndefined() - await page.getByRole('button', { name: /^选择模型/ }).click() - await page.getByRole('menuitem', { name: /^推理等级/ }).click() - const last = menu.getByRole('menuitemradio').last() - await expect.poll(() => last.getAttribute('aria-checked')).toBe('false') + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: 2.5 }) await expect.poll(() => page.evaluate(() => window.visualViewport!.scale)).toBe(2.5) - expect(await menu.getByRole('menuitemradio').count()).toBeGreaterThanOrEqual(7) - await expect.poll(() => last.evaluate((row) => { - const scroller = row.parentElement! + expect(Number(await slider.getAttribute('max'))).toBeGreaterThanOrEqual(7) + expect(await menu.getByRole('group', { name: '推理等级', exact: true }).getByRole('button').count()).toBe(0) + await expect.poll(() => slider.evaluate((range) => { + const scroller = range.closest('[data-model-menu-root]')! scroller.scrollTop = scroller.scrollHeight return { overflow: getComputedStyle(scroller).overflowY, overflows: scroller.scrollHeight > scroller.clientHeight, moved: scroller.scrollTop > 0 } })).toEqual({ overflow: 'auto', overflows: scrolls, moved: scrolls }) - await expect.poll(() => last.evaluate((row) => { - const rect = row.getBoundingClientRect() - const viewport = row.parentElement!.getBoundingClientRect() + await expect.poll(() => slider.evaluate((range) => { + const rect = range.getBoundingClientRect() + const viewport = range.closest('[data-model-menu-root]')!.getBoundingClientRect() return rect.top >= viewport.top - 1 && rect.bottom <= viewport.bottom + 1 })).toBe(true) - const target = await last.evaluate((row) => { - const rect = row.getBoundingClientRect() + const target = await slider.evaluate((range) => { + const rect = range.getBoundingClientRect() const viewport = window.visualViewport! return { - left: Math.max(0, Math.min(window.innerWidth - viewport.width, rect.left + rect.width / 2 - viewport.width / 2)), + left: Math.max(0, Math.min(window.innerWidth - viewport.width, rect.right - 8 - viewport.width / 2)), top: Math.max(0, Math.min(window.innerHeight - viewport.height, rect.top + rect.height / 2 - viewport.height / 2)), offsetLeft: viewport.offsetLeft, offsetTop: viewport.offsetTop, } }) - // Pan from the page margin so wheel input cannot scroll the list instead. + // Pan from the page margin so wheel input cannot scroll the menu instead. await cdp.send('Input.synthesizeScrollGesture', { x: 1, y: 1, xDistance: target.offsetLeft - target.left, yDistance: target.offsetTop - target.top, gestureSourceType: 'mouse', speed: 800, }) - await expect.poll(() => last.evaluate((row) => { - const rect = row.getBoundingClientRect() + await expect.poll(() => slider.evaluate((range) => { + const rect = range.getBoundingClientRect() const viewport = window.visualViewport! - const x = rect.left + rect.width / 2 - viewport.offsetLeft + const x = rect.right - 8 - viewport.offsetLeft const y = rect.top + rect.height / 2 - viewport.offsetTop return x >= 0 && x < viewport.width && y >= 0 && y < viewport.height })).toBe(true) - // Dispatch touch without locator auto-scrolling the last row into view. - const point = await last.evaluate((row) => { - const rect = row.getBoundingClientRect() + // Native touch must select the last stop without locator auto-scrolling. + const point = await slider.evaluate((range) => { + const rect = range.getBoundingClientRect() const viewport = window.visualViewport! - return { x: rect.left + rect.width / 2 - viewport.offsetLeft, + return { x: rect.right - 8 - viewport.offsetLeft, y: rect.top + rect.height / 2 - viewport.offsetTop } }) await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [point] }) await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }) await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection()).toMatchObject({ reasoningEffort: 'max' }) + expect(await menu.isVisible()).toBe(true) + await expect.poll(() => slider.getAttribute('aria-valuetext')).toBe('Max') + await page.keyboard.press('Escape') await menu.waitFor({ state: 'detached' }) } } finally { diff --git a/apps/web/tests/plugin-manager.e2e.ts b/apps/web/tests/plugin-manager.e2e.ts index 66bd3cfb1d..3c606b7624 100644 --- a/apps/web/tests/plugin-manager.e2e.ts +++ b/apps/web/tests/plugin-manager.e2e.ts @@ -1191,6 +1191,7 @@ describe('web e2e: plugin manager', () => { await teamPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await connectFreshWorkspaceZh(teamPage, scaffold.workspaceCwd) await teamPage.getByRole('button', { name: /^选择模型/u }).click() + await teamPage.getByRole('menuitem', { name: '智能体团队协作 关', exact: true }).click() const mode = teamPage.getByRole('switch', { name: '启用智能体团队协作', exact: true }) await mode.waitFor() expect(await mode.getAttribute('aria-checked')).toBe('false') diff --git a/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md b/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md index 07a6ac96dc..0522d13274 100644 --- a/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md +++ b/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md @@ -1,10 +1,9 @@ ## Menu -- menu "模型与推理等级": - - menuitem "模型 DeepSeek-V4-Flash" +- menu "智能体团队协作": - text: 启用智能体团队协作 - - button "关于智能体团队协作" - switch "启用智能体团队协作" [checked] + - paragraph: 通过共享任务板协调多个智能体的分工与进度,复杂任务表现更佳,token 开销也相应更高。 ## Confirmation diff --git a/apps/web/tests/snapshots/agent-team-panel/info.expected.md b/apps/web/tests/snapshots/agent-team-panel/info.expected.md index 5e675607a5..d1171d7e32 100644 --- a/apps/web/tests/snapshots/agent-team-panel/info.expected.md +++ b/apps/web/tests/snapshots/agent-team-panel/info.expected.md @@ -1 +1,12 @@ -- tooltip "Coordinate work and progress across agents with a shared task board for better results on complex tasks, with correspondingly higher token costs." +## Root + +- menu "Model and reasoning effort": + - menuitem "Model DeepSeek-V4-Flash" + - menuitem "Agent teamwork Off" + +## Team settings + +- menu "Agent teamwork": + - text: Enable agent teamwork + - switch "Enable agent teamwork" + - paragraph: Coordinate work and progress across agents with a shared task board for better results on complex tasks, with correspondingly higher token costs. diff --git a/packages/client/ui-agent-team/README.i18n.yaml b/packages/client/ui-agent-team/README.i18n.yaml index 3f894b097c..a438e29119 100644 --- a/packages/client/ui-agent-team/README.i18n.yaml +++ b/packages/client/ui-agent-team/README.i18n.yaml @@ -15,14 +15,14 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-agent-team/use-this-package: - en: d502ab38773eef34 - zh: e1f9c4edbc74c38f + en: 1bb905cfddfc8686 + zh: f3996e9b43e2b06b /deepseek-ai-dsh-client-ui-agent-team/use-this-package/inspect-the-task-board: en: 2f606827b3ab14bc zh: 7f713d10268e7498 /deepseek-ai-dsh-client-ui-agent-team/understand-the-implementation: - en: 9b0b6a8505a9ebbf - zh: beb5d89f80463b3e + en: 7eda4383f70987f8 + zh: 84de71637336d63c /deepseek-ai-dsh-client-ui-agent-team/further-exploration: en: 4d9214370681b02e zh: 4acb21b9ecf25e85 diff --git a/packages/client/ui-agent-team/README.md b/packages/client/ui-agent-team/README.md index 7e87010dcb..bd556a4873 100644 --- a/packages/client/ui-agent-team/README.md +++ b/packages/client/ui-agent-team/README.md @@ -25,7 +25,7 @@ This package displays shared tasks below the Subagent tree in one header panel. ## Use this package -In the root conversation’s model and reasoning menu, turn on **Enable agent teamwork**. New Sessions default to off. While enabled, open the root conversation’s Subagent control to see members above shared tasks. Child conversations keep subagent navigation without a task board or Team switch, including before their subagent address is discovered. The entry is hidden when both the subagent catalog and shared tasks are empty; catalog and task-record errors remain accessible. Section headers appear only when Team mode is enabled, at least one nondeleted shared task exists, and the task footer is available. In that case, the noncollapsible Subagents section remains above shared tasks even when its catalog is empty. Otherwise, the menu shows only subagent navigation, without section headers, a shared-task module, empty-state copy, or a divider. Turning it off retains tasks and subagents. The entire Team row highlights on hover and toggles the selection when clicked, except for its independent information button. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving. The adjacent information button explains shared-task coordination and additional token use on hover, keyboard focus, or click/tap without changing the selection. Escape or an outside press dismisses the explanation. +In the root conversation’s model and reasoning menu, select **Agent teamwork** to open its settings page, then turn on **Enable agent teamwork**. The root row shows only the saved On/Off state and opens the page without changing the selection; the settings page places the switch above the full explanation. New Sessions default to off. While enabled, open the root conversation’s Subagent control to see members above shared tasks. Child conversations keep subagent navigation without a task board or Team switch, including before their subagent address is discovered. The entry is hidden when both the subagent catalog and shared tasks are empty; catalog and task-record errors remain accessible. Section headers appear only when Team mode is enabled, at least one nondeleted shared task exists, and the task footer is available. In that case, the noncollapsible Subagents section remains above shared tasks even when its catalog is empty. Otherwise, the menu shows only subagent navigation, without section headers, a shared-task module, empty-state copy, or a divider. Turning it off retains tasks and subagents. The settings page shows the shared-task coordination, complex-task results, and token-cost explanation as ordinary text, without an information tooltip. Its entire switch row highlights on hover and toggles the selection when clicked. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving. Saving uses the [Switch pending state](../ui-primitives/README.md#component-catalog), so a keyboard-activated switch keeps focus without accepting another change. Turning off the menu switch requires confirmation after the Session records a model request; a model choice alone does not require it. The switch waits while request history is unavailable. The dialog explains the tool, coordination, and possible cache effects without deleting task records. Cancel, Escape, or closing the dialog leaves Team mode unchanged. Dismissing the dialog returns focus to the model selector. Confirmation targets the originating Session, waits for the save, and keeps failures visible for retry; it does not depend on the model menu remaining open. Team mode has no slash command; menu changes create no `command/run` or `command/done` records. @@ -47,7 +47,7 @@ The noncollapsible Shared tasks header uses a Checklist icon and completed, in-p
Implementation internals — click to expand -The Client export registers its locale dictionaries and subagent-catalog and model-menu slots through Cordis effects; it mounts no Remote namespace. Disposing the plugin fiber removes its registrations. +The Client export registers its locale dictionaries and subagent-catalog and model-menu slots through Cordis effects; it mounts no Remote namespace. The [model menu](../ui-model-selection/README.md#use-this-package) owns page navigation and focus return; Team contributes the root summary through `conversation.input.model.options` and settings through `conversation.input.model.page` with key `agent-team`. Disposing the plugin fiber removes its registrations. The Subagent catalog owns the shared panel, scrolling, hover, keyboard, and dismissal interactions. This package contributes the task section only below the root conversation’s tree. The board reads the current Session’s mode and tasks through `useProjection('agentTeam')`. An available, enabled projection supplies the task section only when it contains nondeleted tasks; a projection failure can render independently without a task section. Task IDs, dependencies, readiness, write scopes, and write scope warnings remain in task data but are not displayed as detail fields; blocked pending tasks still use the warning glyph. diff --git a/packages/client/ui-agent-team/README.zh.md b/packages/client/ui-agent-team/README.zh.md index c0db84fe78..115fb82e4c 100644 --- a/packages/client/ui-agent-team/README.zh.md +++ b/packages/client/ui-agent-team/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -在根会话的模型与推理等级菜单中打开**启用智能体团队协作**。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。团队设置整行在悬停时高亮,点击可切换状态,但独立的信息按钮除外。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。旁边的信息按钮可通过悬停、键盘聚焦或点击/轻触查看共享任务协作与额外 token 消耗的说明,不改变开关状态。按 Escape 或点击外部可关闭说明。 +在根会话的模型与推理等级菜单中选择**智能体团队协作**,进入二级设置页后打开**启用智能体团队协作**。一级行只显示已保存的开/关状态,点击仅进入页面,不改变选择;二级页面将开关放在完整说明文字上方。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。设置页以普通正文显示共享任务协调、复杂任务效果与 token 开销的说明,不使用信息 tooltip。开关所在整行在悬停时高亮,点击可切换状态。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。保存时使用 [Switch 的 pending 状态](../ui-primitives/README.zh.md#component-catalog),因此键盘激活的开关保留焦点,但不接受再次切换。 会话记录过模型请求后,从菜单开关停用团队需要确认;仅选择模型不会触发确认。请求历史尚未加载时,开关暂不可操作。弹窗说明工具、协作与可能的缓存影响,不会删除任务记录。取消、按 Escape 或关闭弹窗都保持团队状态不变。弹窗关闭后,焦点回到模型选择按钮。确认操作绑定到最初的会话,等待保存完成,失败时保留错误供重试,不依赖模型菜单保持打开。Team 模式没有斜杠命令;菜单切换不会生成 `command/run` 或 `command/done` 记录。 @@ -47,7 +47,7 @@ Chat 隐藏历史 `/team on` 和 `/team off` 记录中尚未完成或执行成
实现细节——点击展开 -Client export 通过 Cordis effect 注册语言字典、子代理目录与模型菜单 slot;它不挂载 Remote namespace。销毁插件 fiber 会移除这些注册。 +Client export 通过 Cordis effect 注册语言字典、子代理目录与模型菜单 slot;它不挂载 Remote namespace。[模型菜单](../ui-model-selection/README.zh.md#use-this-package)负责页面导航和焦点返回;Team 通过 `conversation.input.model.options` 提供一级摘要,并通过 `conversation.input.model.page` 的 `agent-team` 键提供设置内容。销毁插件 fiber 会移除这些注册。 Subagent 目录负责共享面板的滚动、悬停、键盘和关闭交互。本包仅在根会话的树下方提供任务区。任务板通过 `useProjection('agentTeam')` 读取当前 Session 的模式与任务;仅当投影可用、已开启且含有未删除的任务时才显示任务区;投影错误可独立显示,不需要任务区。任务 ID、依赖、准备状态、写入范围及其提示仍保留在任务数据中,但不作为详情字段显示;被依赖阻塞的 pending 任务仍使用 warning 图标。 diff --git a/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css b/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css index 75eedfb3e7..44916c8f26 100644 --- a/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css +++ b/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css @@ -1,3 +1,63 @@ +.summary { + display: flex; + align-items: center; + gap: 8px; + box-sizing: border-box; + width: 100%; + min-height: 34px; + padding: 7px 8px; + border: 0; + border-radius: var(--dsw-radius-md); + background: transparent; + color: var(--dsw-alias-label-primary); + font-family: inherit; + font-size: 13px; + font-weight: 400; + line-height: 20px; + text-align: start; + cursor: pointer; +} + +.summary:disabled { + opacity: 0.5; + cursor: default; +} + +.summary:focus-visible { + outline: none; + background: var(--dsw-alias-interactive-bg-hover); +} + +.summaryLabel { + flex: 1; + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +.state, +.chevron { + flex: none; + color: var(--dsw-alias-label-secondary); +} + +.page { + display: flex; + flex-direction: column; + gap: 8px; + min-width: 0; +} + +.description { + margin: 0; + padding: 4px 8px; + color: var(--dsw-alias-label-secondary); + font-size: 13px; + line-height: 20px; + overflow-wrap: anywhere; +} + .row { position: relative; display: flex; @@ -13,25 +73,14 @@ } .label { - display: inline-flex; - align-items: center; - gap: 4px; min-width: 0; + overflow-wrap: anywhere; } -.infoButton { - position: relative; - z-index: 1; - flex: none; - width: 20px; - height: 20px; - padding: 0; - color: var(--dsw-alias-label-caption); -} - -/* Extend the native switch hit target without nesting the information button. */ +/* The switch owns the whole row's pointer target. */ .row .toggle { position: static; + flex: none; } .toggle::after { @@ -46,6 +95,7 @@ } @media (hover: hover) { + .summary:not(:disabled):hover, .row:has(.toggle:not(:disabled)):hover { background: var(--dsw-alias-interactive-bg-hover); } diff --git a/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx b/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx index cd0d3dcafa..15f6c93cae 100644 --- a/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx +++ b/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx @@ -1,7 +1,7 @@ -/** Session-owned Agent Teams selection in the model and reasoning menu. */ +/** Session-owned Agent Teams summary and settings inside the model menu. */ import { useState } from 'react' -import { Button, IconInfoOutlineRegular, Switch, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' +import { IconChevronRightOutlineRegular, Switch } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import type {} from '@deepseek-ai/dsh-client-ui-model-selection/client' import type {} from '@deepseek-ai/dsh-agent-team/client' @@ -9,40 +9,75 @@ import type {} from '@deepseek-ai/dsh-agent' import type { NS } from './locales.ts' import css from './TeamModeToggle.module.css' -/** Session selection callbacks supplied by the Client plugin. */ -export interface TeamModeToggleInjected { +/** Session selection callbacks supplied to the Team settings page. */ +export interface TeamModePageInjected { /** Save the selection; null means success, otherwise the string describes the failure. */ selectTeamMode: (enabled: boolean) => Promise /** Open a Session-targeted confirmation outside this menu. */ requestDisableConfirmation: () => void } -/** Full props of the model-menu Team switch. */ -export type TeamModeToggleProps = PropsRuntime<'conversation.input.model.options'> - & PropsLocale & TeamModeToggleInjected +/** Full props of the model-menu Team summary. */ +export type TeamModeToggleProps = PropsRuntime<'conversation.input.model.options'> & PropsLocale + +/** Full props of the model-menu Team settings page. */ +export type TeamModePageProps = PropsRuntime<'conversation.input.model.page'> + & PropsLocale & TeamModePageInjected /** - * Render the saved selection without an optimistic update. - * @param props - Session projection, menu state, localized copy, and selection callback. - * @returns the Team switch when the capability projection is available. + * Show the saved Team state and open its settings without changing the mode. + * @param props - Session projection, page navigation, and locale. + * @returns the summary when Team mode is available on a root Session. */ export function TeamModeToggle(props: TeamModeToggleProps) { const addressedChild = props.useSession(snapshot => snapshot.subagent !== null) const listedChild = props.useSessions(state => state.byId[props.sessionId]?.origin === 'subagent') if (addressedChild || listedChild) return null - return + return +} + +function RootTeamModeSummary({ useProjection, locked, openPage, t }: TeamModeToggleProps) { + const mode = useProjection('agentTeam') + if (mode === undefined) return null + return ( + + ) +} + +/** + * Present the explanation and persisted Team switch for a root Session. + * @param props - Session projections, mode operations, menu dismissal, and locale. + * @returns the Team settings content when its projection is available. + */ +export function TeamModePage(props: TeamModePageProps) { + const addressedChild = props.useSession(snapshot => snapshot.subagent !== null) + const listedChild = props.useSessions(state => state.byId[props.sessionId]?.origin === 'subagent') + if (addressedChild || listedChild) return null + return } /** Read and change the selection only for root Sessions. */ -function RootTeamModeToggle({ +function RootTeamModePage({ useProjection, locked, dismiss, reportFailure, selectTeamMode, requestDisableConfirmation, t, -}: TeamModeToggleProps) { +}: TeamModePageProps) { const mode = useProjection('agentTeam') const modelSelection = useProjection('modelSelection') const [pending, setPending] = useState(false) if (mode === undefined) return null const select = (enabled: boolean): void => { - if (!enabled && modelSelection !== undefined && modelSelection.lastUsed !== null) { + if (locked || pending || modelSelection === undefined) return + if (!enabled && modelSelection.lastUsed !== null) { dismiss() requestDisableConfirmation() return @@ -55,16 +90,13 @@ function RootTeamModeToggle({ }).finally(() => { setPending(false) }) } return ( -
- - {t('mode.label')} - - - - - +
+
+ {t('mode.label')} + +
+

{t('mode.description')}

) } diff --git a/packages/client/ui-agent-team/src/client/locales.ts b/packages/client/ui-agent-team/src/client/locales.ts index 0c5b29a4fb..8f4ed615a6 100644 --- a/packages/client/ui-agent-team/src/client/locales.ts +++ b/packages/client/ui-agent-team/src/client/locales.ts @@ -15,7 +15,8 @@ export const zh = { 'command.failedReason': '执行失败:{reason}', trigger: '任务板', 'mode.label': '启用智能体团队协作', - 'mode.infoLabel': '关于智能体团队协作', + 'mode.on': '开', + 'mode.off': '关', 'mode.description': '通过共享任务板协调多个智能体的分工与进度,复杂任务表现更佳,token 开销也相应更高。', 'mode.failed': '无法确认智能体团队协作设置已保存,请重试:{message}', 'disable.title': '确认停用智能体团队协作?', @@ -52,7 +53,8 @@ export const en = { 'command.failedReason': 'Failed: {reason}', trigger: 'Task board', 'mode.label': 'Enable agent teamwork', - 'mode.infoLabel': 'About agent teamwork', + 'mode.on': 'On', + 'mode.off': 'Off', 'mode.description': 'Coordinate work and progress across agents with a shared task board for better results on complex tasks, with correspondingly higher token costs.', 'mode.failed': 'Could not confirm the agent teamwork setting was saved. Try again: {message}', 'disable.title': 'Disable agent teamwork?', @@ -85,7 +87,8 @@ export const ja = { 'command.failed': '実行失敗', 'command.failedReason': '実行失敗: {reason}', 'mode.label': 'エージェント連携を有効にする', - 'mode.infoLabel': 'エージェント連携について', + 'mode.on': 'オン', + 'mode.off': 'オフ', 'mode.description': '共有タスクボードで複数のエージェントの分担と進捗を調整します。複雑なタスクでより良い結果が得られますが、その分トークンのコストも高くなります。', 'mode.failed': 'エージェント連携の設定が保存されたことを確認できませんでした。再試行してください: {message}', 'disable.title': 'エージェント連携を無効にしますか?', @@ -119,7 +122,8 @@ export const es = { 'command.failed': 'Error', 'command.failedReason': 'Error: {reason}', 'mode.label': 'Activar colaboración entre agentes', - 'mode.infoLabel': 'Acerca de la colaboración entre agentes', + 'mode.on': 'Activada', + 'mode.off': 'Desactivada', 'mode.description': 'Coordina el trabajo y el progreso de varios agentes mediante un tablero de tareas compartido, con mejores resultados en tareas complejas y un coste de tokens proporcionalmente mayor.', 'mode.failed': 'No se pudo confirmar que se guardó la configuración de colaboración entre agentes. Inténtalo de nuevo: {message}', 'disable.title': '¿Desactivar la colaboración entre agentes?', @@ -153,7 +157,8 @@ export const fr = { 'command.failed': 'Échec', 'command.failedReason': 'Échec : {reason}', 'mode.label': 'Activer la collaboration entre agents', - 'mode.infoLabel': 'À propos de la collaboration entre agents', + 'mode.on': 'Activée', + 'mode.off': 'Désactivée', 'mode.description': 'Coordonnez la répartition du travail et la progression de plusieurs agents via un tableau de tâches partagé, pour de meilleurs résultats sur les tâches complexes, avec un coût en tokens plus élevé en contrepartie.', 'mode.failed': 'Impossible de confirmer l’enregistrement du réglage de collaboration entre agents. Réessayez : {message}', 'disable.title': 'Désactiver la collaboration entre agents ?', @@ -187,7 +192,8 @@ export const de = { 'command.failed': 'Fehlgeschlagen', 'command.failedReason': 'Fehlgeschlagen: {reason}', 'mode.label': 'Agentenzusammenarbeit aktivieren', - 'mode.infoLabel': 'Über Agentenzusammenarbeit', + 'mode.on': 'Ein', + 'mode.off': 'Aus', 'mode.description': 'Koordiniert die Arbeitsteilung und den Fortschritt mehrerer Agenten über eine gemeinsame Aufgabenübersicht. Erzielt bessere Ergebnisse bei komplexen Aufgaben, bei entsprechend höheren Tokenkosten.', 'mode.failed': 'Das Speichern der Einstellung zur Agentenzusammenarbeit konnte nicht bestätigt werden. Erneut versuchen: {message}', 'disable.title': 'Agentenzusammenarbeit deaktivieren?', @@ -221,7 +227,8 @@ export const ru = { 'command.failed': 'Ошибка', 'command.failedReason': 'Ошибка: {reason}', 'mode.label': 'Включить совместную работу агентов', - 'mode.infoLabel': 'О совместной работе агентов', + 'mode.on': 'Вкл.', + 'mode.off': 'Выкл.', 'mode.description': 'Координируйте распределение работы и прогресс нескольких агентов с помощью общей доски задач: лучшие результаты в сложных задачах при соответственно более высоких затратах на токены.', 'mode.failed': 'Не удалось подтвердить сохранение настройки совместной работы агентов. Повторите попытку: {message}', 'disable.title': 'Отключить совместную работу агентов?', @@ -255,7 +262,8 @@ export const pt = { 'command.failed': 'Falha', 'command.failedReason': 'Falha: {reason}', 'mode.label': 'Ativar colaboração entre agentes', - 'mode.infoLabel': 'Sobre a colaboração entre agentes', + 'mode.on': 'Ativada', + 'mode.off': 'Desativada', 'mode.description': 'Coordene a divisão do trabalho e o progresso de vários agentes com um quadro de tarefas compartilhado, para melhores resultados em tarefas complexas, com custos de tokens proporcionalmente maiores.', 'mode.failed': 'Não foi possível confirmar que a configuração de colaboração entre agentes foi salva. Tente novamente: {message}', 'disable.title': 'Desativar a colaboração entre agentes?', diff --git a/packages/client/ui-agent-team/src/client/mount.ts b/packages/client/ui-agent-team/src/client/mount.ts index 833267e39e..8f22910564 100644 --- a/packages/client/ui-agent-team/src/client/mount.ts +++ b/packages/client/ui-agent-team/src/client/mount.ts @@ -11,7 +11,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-model-selection/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { TeamDisableConfirmation, type TeamDisableConfirmationInjected, type TeamDisableRequest } from './TeamDisableConfirmation.tsx' -import { TeamModeToggle, type TeamModeToggleInjected } from './TeamModeToggle.tsx' +import { TeamModePage, TeamModeToggle, type TeamModePageInjected } from './TeamModeToggle.tsx' import { TeamBoard } from './TeamBoard.tsx' import { TeamCommandRow } from './TeamCommandRow.tsx' import { en, ja, es, fr, de, ru, pt, NS, zh, type TeamKey } from './locales.ts' @@ -58,11 +58,14 @@ export function registerAgentTeamUi(ctx: ClientContext): void { name: 'conversation.input.model.options', id: 'agent-team', locale: NS, - inject: (sessionId): TeamModeToggleInjected => ({ + }, TeamModeToggle)) + yield scope.slots.inject('conversation.input.model.page', () => scope.slots.register({ + name: 'conversation.input.model.page', key: 'agent-team', locale: NS, + inject: (sessionId): TeamModePageInjected => ({ selectTeamMode: enabled => selectTeamMode(sessionId, enabled), requestDisableConfirmation: () => { disableRequest.set({ sessionId }) }, }), - }, TeamModeToggle)) + }, TeamModePage)) }) }) ctx.slots.inject('conversation.session.header.actions.subagent.footer', () => ctx.slots.register({ diff --git a/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts b/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts index ba964a033f..c5bab1fe0a 100644 --- a/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts @@ -2,7 +2,7 @@ import { Context } from '@deepseek-ai/cordis' import { describe, expect, it, onTestFinished, vi } from 'vitest' import { SessionId } from '@deepseek-ai/dsh-session/types' import { RemoteError, TestRemote } from '@deepseek-ai/dsh-client-test-runtime' -import { TeamModeToggle, type TeamModeToggleInjected } from '../src/client/TeamModeToggle.tsx' +import { TeamModePage, TeamModeToggle, type TeamModePageInjected } from '../src/client/TeamModeToggle.tsx' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' import { TeamBoard } from '../src/client/TeamBoard.tsx' @@ -62,21 +62,30 @@ describe('task-board browser plugin', () => { await b.fiber.dispose() }) - it('registers the mode switch when Agent Teams arrives and reports each execution outcome', async () => { + it('registers the summary and settings page when Agent Teams arrives and reports each execution outcome', async () => { const b = await bench() b.ctx.slots.register({ name: 'conversation.input.model', - children: { 'conversation.input.model.options': { kind: 'list', scope: 'session' } }, + children: { + 'conversation.input.model.options': { kind: 'list', scope: 'session' }, + 'conversation.input.model.page': { kind: 'keyed', scope: 'session' }, + }, } as never, () => null) const entry = () => b.ctx.slots.entries('conversation.input.model.options') .find(candidate => candidate.component === TeamModeToggle) + const page = () => b.ctx.slots.entries('conversation.input.model.page') + .find(candidate => candidate.component === TeamModePage) expect(entry()).toBeUndefined() + expect(page()).toBeUndefined() const setEnabled = vi.fn() new TestRemote(b.ctx, { agentTeams: { setEnabled } }) - await vi.waitFor(() => { expect(entry()).toBeDefined() }) - const injected = entry()!.inject as (sessionId: SessionId) => Record + await vi.waitFor(() => { expect(entry()).toBeDefined(); expect(page()).toBeDefined() }) + expect(entry()).toMatchObject({ options: { id: 'agent-team' }, locale: 'agent-team' }) + expect(entry()!.inject).toBeUndefined() + expect(page()).toMatchObject({ options: { key: 'agent-team' }, locale: 'agent-team' }) + const injected = page()!.inject as (sessionId: SessionId) => Record const value: object = injected(SessionId('chosen-session')) - const mode = value as TeamModeToggleInjected + const mode = value as TeamModePageInjected setEnabled.mockResolvedValueOnce({ ok: true, value: undefined }) await expect(mode.selectTeamMode(true)).resolves.toBeNull() expect(setEnabled).toHaveBeenLastCalledWith('chosen-session', true) @@ -104,6 +113,7 @@ describe('task-board browser plugin', () => { mode.requestDisableConfirmation() await b.fiber.dispose() expect(entry()).toBeUndefined() + expect(page()).toBeUndefined() expect(overlayEntry()).toBeUndefined() expect(request.getSnapshot()).toBeNull() }) diff --git a/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx b/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx index 13a1da8450..9fa08dacc9 100644 --- a/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx +++ b/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx @@ -1,18 +1,17 @@ // @vitest-environment jsdom -import { afterEach, expect, it, vi } from 'vitest' +import { afterEach, expect, it, onTestFinished, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { SessionId } from '@deepseek-ai/dsh-session' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' -import { TeamModeToggle, type TeamModeToggleProps } from '../src/client/TeamModeToggle.tsx' +import { TeamModePage, TeamModeToggle, type TeamModePageProps, type TeamModeToggleProps } from '../src/client/TeamModeToggle.tsx' import { de, en, es, fr, ja, pt, ru, zh } from '../src/client/locales.ts' -afterEach(() => { - cleanup() - vi.unstubAllGlobals() -}) +afterEach(cleanup) -function props(enabled: boolean | undefined, selectTeamMode = vi.fn(async () => null as string | null), child?: 'addressed' | 'listed', requestedModel: boolean | 'loading' = false): TeamModeToggleProps { +type TestProps = TeamModePageProps & TeamModeToggleProps + +function props(enabled: boolean | undefined, selectTeamMode = vi.fn(async () => null as string | null), child?: 'addressed' | 'listed', requestedModel: boolean | 'loading' = false): TestProps { return { sessionId: SessionId('root'), useSession: (select: (value: { subagent: object | null }) => unknown) => select({ subagent: child === 'addressed' ? {} : null }), @@ -20,69 +19,112 @@ function props(enabled: boolean | undefined, selectTeamMode = vi.fn(async () => useProjection: (key: string) => key === 'modelSelection' ? requestedModel === 'loading' ? undefined : { lastUsed: requestedModel ? { provider: 'mock', model: 'mock' } : null, next: { provider: 'mock', model: 'mock' } } : enabled === undefined ? undefined : { enabled, tasks: [] }, - locked: false, dismiss: vi.fn(), reportFailure: vi.fn(), selectTeamMode, requestDisableConfirmation: vi.fn(), + locked: false, openPage: vi.fn(), dismiss: vi.fn(), reportFailure: vi.fn(), selectTeamMode, requestDisableConfirmation: vi.fn(), t: makeTranslate(zh), - } as TeamModeToggleProps + } as TestProps } -it('renders only available mode and waits for persisted state before displaying a new selection', async () => { - let finish!: (result: string | null) => void - const select = vi.fn(() => new Promise((resolve) => { finish = resolve })) - const view = render() +it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }).flatMap(([locale, dictionary]) => + [false, true].map(enabled => ({ locale, dictionary, enabled })), +))('opens Team settings from the $locale summary without changing mode (enabled: $enabled)', ({ dictionary, enabled }) => { + const input = props(enabled) + render() + const summary = screen.getByRole('menuitem', { name: new RegExp(dictionary['command.title']) }) + expect(summary.textContent).toBe(dictionary['command.title'] + dictionary[enabled ? 'mode.on' : 'mode.off']) + expect(summary.getAttribute('data-model-menu-page')).toBe('agent-team') expect(screen.queryByRole('switch')).toBeNull() - view.rerender() + expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() + expect(screen.queryByText(dictionary['mode.description'])).toBeNull() + fireEvent.click(summary) + expect(input.openPage).toHaveBeenCalledExactlyOnceWith({ key: 'agent-team', title: dictionary['command.title'] }) + expect(input.selectTeamMode).not.toHaveBeenCalled() + expect(input.requestDisableConfirmation).not.toHaveBeenCalled() + expect(input.dismiss).not.toHaveBeenCalled() +}) + +it('keeps summary state projection-owned and blocks navigation while locked', () => { + const input = props(false) + const view = render() + expect(screen.getByText('关')).toBeTruthy() + const lockedInput = props(true) + view.rerender() + expect(screen.getByText('开')).toBeTruthy() + const summary = screen.getByRole('menuitem') + expect(summary.hasAttribute('disabled')).toBe(true) + fireEvent.click(summary) + expect(lockedInput.openPage).not.toHaveBeenCalled() +}) + +it('allows reading settings from the summary while model history loads', () => { + const input = props(false, undefined, undefined, 'loading') + render() + fireEvent.click(screen.getByRole('menuitem')) + expect(input.openPage).toHaveBeenCalledOnce() + expect(input.selectTeamMode).not.toHaveBeenCalled() +}) + +it.each([false, true])('retains focus and blocks repeated writes while waiting for persisted mode (enabled: %s)', async (enabled) => { + const pending = Promise.withResolvers() + onTestFinished(async () => { await act(async () => { pending.resolve(null) }) }) + const select = vi.fn(() => pending.promise) + const view = render() const toggle = screen.getByRole('switch', { name: '启用智能体团队协作' }) + toggle.focus() fireEvent.click(toggle) - expect(select).toHaveBeenCalledWith(true) - expect(toggle.getAttribute('aria-checked')).toBe('false') - expect(toggle.hasAttribute('disabled')).toBe(true) - await act(async () => { finish(null) }) - view.rerender() - expect(toggle.getAttribute('aria-checked')).toBe('true') + expect(select).toHaveBeenCalledExactlyOnceWith(!enabled) + expect(toggle.getAttribute('aria-checked')).toBe(String(enabled)) + expect(toggle.hasAttribute('disabled')).toBe(false) + expect(toggle.getAttribute('aria-disabled')).toBe('true') + expect(toggle.getAttribute('aria-busy')).toBe('true') + expect(document.activeElement).toBe(toggle) + fireEvent.click(toggle) + fireEvent.click(toggle) + expect(select).toHaveBeenCalledTimes(1) + await act(async () => { pending.resolve(null) }) + expect(toggle.getAttribute('aria-checked')).toBe(String(enabled)) + expect(toggle.getAttribute('aria-disabled')).toBeNull() + expect(toggle.getAttribute('aria-busy')).toBeNull() + view.rerender() + expect(toggle.getAttribute('aria-checked')).toBe(String(!enabled)) + expect(document.activeElement).toBe(toggle) }) it.each(['returned', 'error', 'string'])('reports rejected mode writes through the menu host (%s)', async (failure) => { - const p = props(false, vi.fn(async () => { + const input = props(false, vi.fn(async () => { if (failure === 'error') throw new Error('offline') if (failure === 'string') throw 'offline' return 'offline' })) - render() - await act(async () => { fireEvent.click(screen.getByRole('switch')) }) - expect(p.reportFailure).toHaveBeenCalledWith(expect.stringContaining('offline')) + render() + const toggle = screen.getByRole('switch') + toggle.focus() + await act(async () => { fireEvent.click(toggle) }) + expect(document.activeElement).toBe(toggle) + expect(toggle.getAttribute('aria-busy')).toBeNull() + expect(input.reportFailure).toHaveBeenCalledWith(expect.stringContaining('offline')) expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('false') + expect(screen.getByRole('switch').hasAttribute('disabled')).toBe(false) }) it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }).flatMap(([locale, dictionary]) => [false, true].map(locked => ({ locale, dictionary, locked })), -))('opens the $locale explanation without changing Team mode (locked: $locked)', ({ dictionary, locked }) => { - vi.stubGlobal('ResizeObserver', class { - observe() {} - unobserve() {} - disconnect() {} - }) +))('shows the full $locale explanation in the settings page (locked: $locked)', ({ dictionary, locked }) => { const input = props(false) - render() - const info = screen.getByRole('button', { name: dictionary['mode.infoLabel'] }) - expect(info.hasAttribute('disabled')).toBe(false) - fireEvent.click(info) - const tooltip = screen.getByRole('tooltip', { hidden: true }) - expect(tooltip.textContent).toBe(dictionary['mode.description']) - expect(info.getAttribute('aria-describedby')).toBe(tooltip.id) - expect(document.body.contains(tooltip)).toBe(true) - expect(input.selectTeamMode).not.toHaveBeenCalled() - expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('false') - fireEvent.keyDown(info, { key: 'Escape' }) - expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() - fireEvent.click(info) - fireEvent.pointerDown(document.body) + render() + const description = screen.getByText(dictionary['mode.description'], { exact: true }) + expect(description.tagName).toBe('P') expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() + expect(screen.queryByRole('button')).toBeNull() + const toggle = screen.getByRole('switch', { name: dictionary['mode.label'] }) + expect(toggle.compareDocumentPosition(description) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() + expect(toggle.hasAttribute('disabled')).toBe(locked) + expect(toggle.getAttribute('aria-checked')).toBe('false') expect(input.selectTeamMode).not.toHaveBeenCalled() }) -it('requests confirmation before disabling after a recorded model request', () => { +it('dismisses the menu before requesting disable confirmation after a recorded model request', () => { const input = props(true, undefined, undefined, true) - render() + render() fireEvent.click(screen.getByRole('switch')) expect(input.dismiss).toHaveBeenCalledOnce() expect(input.dismiss).toHaveBeenCalledBefore(vi.mocked(input.requestDisableConfirmation)) @@ -93,39 +135,52 @@ it('requests confirmation before disabling after a recorded model request', () = it.each([false, true])('enables directly regardless of model history (requested: %s)', async (requested) => { const input = props(false, undefined, undefined, requested) - render() + render() await act(async () => { fireEvent.click(screen.getByRole('switch')) }) expect(input.selectTeamMode).toHaveBeenCalledWith(true) expect(input.requestDisableConfirmation).not.toHaveBeenCalled() + expect(input.dismiss).not.toHaveBeenCalled() }) it('disables directly when a model is selected but no request has been recorded', async () => { const input = props(true) - render() + render() await act(async () => { fireEvent.click(screen.getByRole('switch')) }) expect(input.selectTeamMode).toHaveBeenCalledWith(false) expect(input.requestDisableConfirmation).not.toHaveBeenCalled() + expect(input.dismiss).not.toHaveBeenCalled() }) -it('waits for model history before allowing the switch to change', () => { +it('waits for model history before allowing the settings switch to change', () => { const input = props(true, undefined, undefined, 'loading') - render() + render() expect(screen.getByRole('switch').hasAttribute('disabled')).toBe(true) fireEvent.click(screen.getByRole('switch')) expect(input.selectTeamMode).not.toHaveBeenCalled() expect(input.requestDisableConfirmation).not.toHaveBeenCalled() }) -it('disables selection while the Session is locked', () => { - render() - expect(screen.getByRole('switch').hasAttribute('disabled')).toBe(true) +it.each([ + { name: 'summary', Component: TeamModeToggle }, + { name: 'settings page', Component: TeamModePage }, +])('hides the $name until the Team projection is available', ({ Component }) => { + const { container } = render() + expect(container.textContent).toBe('') + expect(screen.queryByRole('menuitem')).toBeNull() + expect(screen.queryByRole('switch')).toBeNull() }) -it.each(['addressed', 'listed'] as const)('hides the switch on a child Session (%s)', (source) => { - const input = props(false, undefined, source) - const useProjection = vi.fn((): never => { throw new Error('Child must not read Team mode') }) - render() - expect(screen.queryByRole('switch')).toBeNull() - expect(useProjection).not.toHaveBeenCalled() - expect(input.selectTeamMode).not.toHaveBeenCalled() -}) +it.each([ + { name: 'summary', Component: TeamModeToggle }, + { name: 'settings page', Component: TeamModePage }, +].flatMap(entry => (['addressed', 'listed'] as const).map(child => ({ ...entry, child }))))( + 'hides the $name on a $child child Session', ({ Component, child }) => { + const input = props(false, undefined, child) + const useProjection = vi.fn((): never => { throw new Error('Child must not read Team mode') }) + const { container } = render() + expect(container.textContent).toBe('') + expect(useProjection).not.toHaveBeenCalled() + expect(input.selectTeamMode).not.toHaveBeenCalled() + expect(input.openPage).not.toHaveBeenCalled() + }, +) diff --git a/packages/client/ui-model-selection/README.i18n.yaml b/packages/client/ui-model-selection/README.i18n.yaml index f0b4774867..3d37eb7f75 100644 --- a/packages/client/ui-model-selection/README.i18n.yaml +++ b/packages/client/ui-model-selection/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-model-selection/use-this-package: - en: 0e2230da6a2214a1 - zh: 0452e7556c9175f2 + en: 8caa289a6b9a3987 + zh: 4e68187154ad7a01 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/model-and-effort: - en: cead8d55a9508a8f - zh: d1ef63a880cbec55 + en: 7444798cb92d0f38 + zh: 03edcc1070554437 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/model-label-extensions: en: 8da3af8ae98adbb3 zh: b411b32d6b2b9e04 @@ -27,11 +27,11 @@ en: 7f20428c747ff052 zh: 975e6de728e02fa0 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/selection-failures: - en: 80fc237fa5c829f7 - zh: ecff5c8526f45996 + en: 393aae0df60e2abd + zh: f989d6108a047160 /deepseek-ai-dsh-client-ui-model-selection/understand-the-implementation: - en: c1d14a925c92950f - zh: f80f8169bc283c60 + en: feab134e75f5b2f7 + zh: 66bd58568f58ed4f /deepseek-ai-dsh-client-ui-model-selection/further-exploration: en: 14acd4692e923480 zh: ff89aed852aa0da8 @@ -42,8 +42,8 @@ en: 68e54c00412a40d1 zh: 0ac96f57fd194d96 /deepseek-ai-dsh-client-ui-model-selection/known-limitations-and-deferred-work: - en: 7003aff3aa57e40c - zh: 450d88a5e9332f05 + en: 01a55381300a60c5 + zh: 3561ca742b9272ca /deepseek-ai-dsh-client-ui-model-selection/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/client/ui-model-selection/README.md b/packages/client/ui-model-selection/README.md index ec0aba0d4e..55adbc748d 100644 --- a/packages/client/ui-model-selection/README.md +++ b/packages/client/ui-model-selection/README.md @@ -29,22 +29,24 @@ The Web GUI lets users switch the model and reasoning effort for an existing ses DeepSeek account and API-key routes appear as separate provider groups, each exposing the same configured model catalog. -When no model is selected or the saved selection is absent from the catalog, the composer shows “Select model” in regular weight and hides the reasoning effort caption. Clicking it opens the model list directly; Escape and Shift+Tab close it. An empty catalog hides the model menu from display and the accessibility tree and displays “No models available.” in a status region. +When no model is selected or the saved selection is absent from the catalog, the composer shows “Select model” in regular weight and hides the reasoning effort caption. Clicking it opens the model list directly; Escape closes it. Tab and Shift+Tab traverse its controls and leave the menu at either end. An empty catalog hides the model menu from display and the accessibility tree and displays “No models available.” in a status region. -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 through root and effort rows, or move the model-list highlight without leaving search. Enter and Tab settle the highlighted model or focused row; Escape and `Shift+Tab` leave a drilled pane first and otherwise close back to the trigger. Drilling focuses model search when shown on desktop devices; otherwise it focuses the current model or effort row, or the first enabled row when none is selected. Going back focuses the cell that opened the pane. Phones and tablets leave search unfocused until the user taps it or uses keyboard navigation. The composer shows the catalog name while the selected model is available. Removing a model or provider, including account sign-out, preserves the stored provider, model, and reasoning effort without displaying their IDs. Restoring the catalog entry restores its name and effort caption. +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. In the root menu, `↑`/`↓` move between the model row, reasoning slider, and contributed options. A focused slider keeps arrow, Home, and End keys for its own value; Tab and Shift+Tab move to the adjacent control. In model search, arrows move the highlight and Enter selects it. Tab and Shift+Tab traverse search, its clear button, and the highlighted model without selecting; focused buttons activate with Enter or Space. Detail pages have no visible title or Back button. Escape returns to the root and restores the invoking row's focus; pressing Escape again closes the menu and focuses its trigger. Returning from the model list with Escape or after a successful model selection restores focus to the root model row without its grey background. Subsequent pointer movement or Tab navigation restores normal hover and focus styling. Phones and tablets leave model search unfocused until the user taps it or uses keyboard navigation. Removing a model or provider, including sign-out, preserves the saved route and effort without displaying their IDs; restoring its catalog entry restores its name and caption. -Mouse selection uses native browser clicks, including their cancellation behavior; a press alone never selects. Opening the root menu focuses its trigger, and clicking the trigger again closes the menu and returns focus there. Root rows and the search-clear button show the same fill for keyboard focus and hover, without a native outline. Selecting a model or effort returns focus to the trigger without a focus ring; leaving the trigger or reopening the menu restores its normal focus indication. While a selection from either entry is pending, focus stays on the trigger, the trigger shows a spinner in place of its chevron, and each row whose value the selection carries shows one in place of its check; a rejected selection leaves the menu open. Tab returns to model search with the current model highlighted when search is shown, otherwise to the current row. +Mouse selection uses native browser clicks, including their cancellation behavior; a press alone never selects. Opening the root menu focuses its trigger, and clicking the trigger again closes it. Selecting a model returns to the root menu and its model row; changing effort keeps the menu and slider focus in place. While a model selection is pending, the trigger and chosen model-list row show spinners. Pending selections retain their target value and block duplicate submissions without a loading cursor; an effort save also keeps slider focus. A rejected selection leaves the menu and previous selection available for retry. Settings detail pages retain native Tab traversal. ### Model and effort -The button's model menu shows search only when its full catalog contains more than four models; smaller catalogs support keyboard navigation directly and focus the current model or first enabled row on all devices. The `/model` command always keeps its search field. Both search fields match model names case-insensitively, including nonconsecutive characters in order; leading and trailing spaces are ignored. Within each provider, prefix matches come first, followed by alignment score and then catalog order. Empty groups are hidden. Empty catalogs and queries without matches are announced through a status region. Search keeps focus while arrow keys cycle the highlighted result across provider groups; Enter or Tab selects it. Left and right arrows keep their native caret behavior. Opening highlights the current model or the first available row, and editing the query resets the highlight to the first result. Reopening the model pane clears the query. +The button's model menu shows search only when its full catalog contains more than four models; smaller catalogs support keyboard navigation directly and focus the current model or first enabled row on all devices. The `/model` command always keeps its search field. Both search fields match model names case-insensitively, including nonconsecutive characters in order; leading and trailing spaces are ignored. Within each provider, prefix matches come first, followed by alignment score and then catalog order. Empty groups are hidden. Empty catalogs and queries without matches are announced through a status region. Search keeps focus while arrow keys cycle the highlighted result across provider groups. In the composer menu, Enter selects the result and Tab moves focus without selecting it; the `/model` popup retains its command-menu keyboard behavior. Left and right arrows keep their native caret behavior. Opening highlights the current model or the first available row, and editing the query resets the highlight to the first result. Reopening the model pane clears the query. -Model and reasoning-effort names use weight 400 (regular) in the composer menu, including the selected item. The search field follows the command popup's compact treatment with transparent background and border in both palettes, with no leading icon and a caption-tone placeholder. Its text is 16px on devices with a coarse primary pointer to avoid Safari focus zoom; fine pointers retain 12px. The clear button appears for a nonempty query and restores the full list with focus in the search field. +Model names use weight 400 (regular); the current effort tag uses weight 500. The search field follows the command popup's compact treatment with transparent background and border in both palettes, with no leading icon and a caption-tone placeholder. Its text is 16px on devices with a coarse primary pointer to avoid Safari focus zoom; fine pointers retain 12px. The clear button appears for a nonempty query and restores the full list with focus in the search field. -Both entries group models by provider, with DeepSeek Account first and DeepSeek second; third-party providers retain their catalog order. Both use the shared, asynchronously observed sticky headings from [ui-primitives](../ui-primitives/README.md#understand-the-implementation): transparent at rest, with the theme's 94%-opaque fill only while pinned, and `md` corners outside macOS Desktop. The composer menu shows model and effort names only. Navigation chevrons use `--dsw-alias-menu-icon`. The `/model` popup shows provider names as group headings and model names as rows, without repeating the provider on each row or showing catalog descriptions. Its search placeholder, no-match text, and empty-catalog text use the same localized labels as the composer model menu. The popup applies the selected model's default effort; the composer can then choose any advertised effort. An adapter without reasoning metadata leaves the Effort row absent; there is no arbitrary effort input. +Both entries group models by provider, with DeepSeek Account first and DeepSeek second; third-party providers retain their catalog order. Both use the shared, asynchronously observed sticky headings from [ui-primitives](../ui-primitives/README.md#understand-the-implementation): transparent at rest, with the theme's 94%-opaque fill only while pinned, and `md` corners outside macOS Desktop. The composer menu shows model and effort names only. Navigation chevrons use `--dsw-alias-menu-icon`. The `/model` popup shows provider names as group headings and model names as rows, without repeating the provider on each row or showing catalog descriptions. Its search placeholder, no-match text, and empty-catalog text use the same localized labels as the composer model menu. The popup applies the selected model's default effort; the composer can then choose any advertised effort. An adapter without reasoning metadata leaves the reasoning slider absent; there is no arbitrary effort input. The composer replaces the model and effort text with the Models icon when the expanded controls cannot share one line, and restores the text when space permits. The full selection remains available in the trigger's accessible name, tooltip, and menu. +The 260px-wide root menu places the model name above a centered effort tag and a native slider with discrete stops for the exact model's ordered reasoning choices. The tag uses the default cursor and its text cannot be selected; hovering still shows the localized “Reasoning effort: {effort}” tooltip without adding a Tab stop. Pointer drags preview locally and submit once on release; keyboard adjustments submit on key release. Escape during adjustment cancels the preview, and changing models discards any unfinished gesture. A `Default` stop appears only when the adapter has no configured default effort and submits no explicit effort; it is not a promise of a fixed provider strength. A single supported stop is readable but not draggable. No arbitrary token budget is entered here. + ### Model label extensions `conversation.input.model.label` is a session-scoped, inline `single` slot for the composer trigger (`placement: 'trigger'`), the root menu's current value (`'menu'`), and each model option (`'option'`). Its owner props provide `provider: { id, name }`, the exact catalog `model`, `placement`, and `selected`. Provider names are localized display names; match channels by `provider.id`, and identify a model by the provider/model ID pair. Connection URLs and credentials are not passed to the slot. @@ -61,18 +63,18 @@ Catalog availability does not block sending with a saved selection; request exec When another writer owns the Session, model-selection failures tell the user to quit other running DSH instances and retry. -The session-scoped `conversation.input.model.options` list slot appends controls below model and reasoning selection. Owner props expose `locked`, `reportFailure(message)`, and `dismiss()`, which closes the menu and synchronously focuses its trigger before another overlay opens; contributions read their own projections and supply narrow commands. Enabled switch buttons participate in the menu’s keyboard navigation. +The session-scoped `conversation.input.model.options` list slot appends root options below model and reasoning controls. Its owner props expose `locked`, `reportFailure(message)`, `dismiss()`, and `openPage({ key, title })`. A root option marks its button with `data-model-menu-page` equal to its registration key and opens that key in `conversation.input.model.page`, a session-scoped keyed slot. The menu owner supplies scrolling, Escape navigation, focus return, and an accessible page name from `title`, without a visible title or Back button; the page receives `locked`, `reportFailure`, and `dismiss`, while its owning plugin retains all settings and confirmation logic. `dismiss()` closes the entire menu and focuses its trigger before another overlay opens. ----- ## Understand the implementation -Menus use the shared `MenuSurface` material, including the macOS backing for background blur; custom content follows the [menu rules](../../../docs/web-styling.md#component-rules). The composer menu uses a fixed body portal and CSS Anchor Positioning, which requires browser support for `anchor-name`, `position-anchor`, and `anchor()`. The trigger and menu share a unique anchor name. CSS prefers the position above the trigger with right edges aligned and an 8px gap, and keeps the menu within the layout viewport's 12px insets and desktop frame clearance. The trigger gap is preserved when desktop page zoom reflows the sticky composer. No JavaScript reads the trigger rectangle or tracks viewport changes for this placement. Pinch zoom scales the menu with the page; it may extend beyond the visual viewport, including while the keyboard is open. Model names ellipsize within the panel width while badges stay visible. Model and reasoning-effort lists scroll vertically within the panel height limit. -
Implementation internals — click to expand +Menus use the shared `MenuSurface` material, including the macOS backing for background blur; custom content follows the [menu rules](../../../docs/web-styling.md#component-rules). The composer menu uses a fixed body portal and CSS Anchor Positioning, which requires browser support for `anchor-name`, `position-anchor`, and `anchor()`. The trigger and menu share a unique anchor name. CSS prefers the position above the trigger with right edges aligned and an 8px gap, and keeps the menu within the layout viewport's 12px insets and desktop frame clearance. The trigger gap is preserved when desktop page zoom reflows the sticky composer. No JavaScript reads the trigger rectangle or tracks viewport changes for this placement. Pinch zoom scales the menu with the page; it may extend beyond the visual viewport, including while the keyboard is open. Model names ellipsize within the panel width while badges stay visible. The root controls, model list, and settings pages have their own scroll area inside the panel height limit. + The composer `ModelSelect` and `/model` option builder share [provider ordering](src/client/provider-order.ts), while both searches use `rankByName` within each provider. The command supplies optional groups and `searchMode: 'fuzzy-label'` through the [popupSelect API](../ui-commands/README.md#use-this-package); both entries use `MenuGroup` and rebuild its sticky observer when the rendered groups change. The command popup fills the composer overlay, while the button retains its compact menu. Two entries over ONE per-session directory owned by `ModelDirectoryResolver` (`ctx.modelDirectories`): the `/model` popupSelect contribution (registered through `ctx.commandUi`) and the composer's named `conversation.input.model` seat both load the session's available directory through `session.models` and submit through `session.selectModel` via the same `ModelDirectory` instance, so a switch made in either entry is what the other shows next. Directory loads and selections share a generation counter so an older response never overwrites a newer one. The directory publishes the latest submitted selection as `pending` until it settles or a connection reset invalidates it; a connection reset drops every resident projection and repulls the Host-restored selection before display. Directories are per-session, resolved lazily, and disposed with the session scope; addressed subagent sessions expose neither entry. Every resident directory refetches directly on forwarded `llm/adapters-updated`, `llm/models-updated`, `settings/document-updated`, and credential update events. @@ -110,7 +112,7 @@ These limits define the current model surface. They are current package constrai - **No create-time or addressed-subagent selection** — both entries require an existing ordinary session's Agent; there is no draft-phase model choice to fold into session creation, and subagent continuation deliberately exposes no independent model-selection contract. - **Directory names are presentation-only** — selection and persistence use provider/model/effort ids; a provider whose catalog or exact-model metadata lookup fails lists as an unselectable failure row until reload. -- **No arbitrary effort input** — the composer offers only the exact model's adapter-advertised levels; an adapter without reasoning metadata leaves the Effort row absent. +- **No arbitrary effort input** — the composer offers only the exact model's adapter-advertised levels; an adapter without reasoning metadata leaves the reasoning slider absent. - **Badges label the composer seat only** — `/model` popup rows, the trigger's accessible name, and its tooltip keep the plain catalog name. diff --git a/packages/client/ui-model-selection/README.zh.md b/packages/client/ui-model-selection/README.zh.md index 864d3ea9ff..f92ff2ffdd 100644 --- a/packages/client/ui-model-selection/README.zh.md +++ b/packages/client/ui-model-selection/README.zh.md @@ -29,22 +29,24 @@ Web GUI 允许用户通过 `/model` 弹窗或 composer 模型控件切换既有 DeepSeek 账号和 API Key 路由显示为独立提供方分组,各自展示相同的已配置模型目录。 -未选择模型或已保存的选择不在目录中时,composer 以常规字重显示“请选择模型”,并隐藏推理强度文案。点击后直接打开模型列表,Escape 和 Shift+Tab 关闭列表。目录为空时,模型菜单不显示,也不进入无障碍树;状态区域显示“暂无可用模型” +未选择模型或已保存的选择不在目录中时,composer 以常规字重显示“请选择模型”,并隐藏推理强度文案。点击后直接打开模型列表,Escape 关闭列表。Tab 和 Shift+Tab 遍历列表内的控件,到达两端时离开菜单。目录为空时,模型菜单不显示,也不进入无障碍树;状态区域显示“暂无可用模型” -与 `ui-conversation` 及命令包一起挂载本插件;composer 随即在待处理指示器旁显示模型位,`/model` 则以弹窗打开同一份目录。模型位菜单打开期间,`↑`/`↓` 在根菜单和推理等级行间移动焦点,或在模型列表中移动高亮并让焦点保留在搜索框。Enter 和 Tab 选定高亮模型或聚焦行;Escape 与 `Shift+Tab` 先退出已下钻的面板,否则关闭并回到触发器。下钻时,桌面设备在显示模型搜索框时聚焦搜索框;其他情况聚焦当前模型或推理强度行,没有选中项时聚焦首个可用行。返回时聚焦打开该面板的格子。手机和平板在用户主动点按搜索框或使用键盘导航前,不会聚焦搜索框。所选模型可用时,composer 显示目录中的模型名称。模型或提供方被删除时(包括账号退登),保留已保存的提供方、模型和推理强度,但不展示其 ID。目录条目恢复后重新显示名称和推理强度。 +与 `ui-conversation` 及命令包一起挂载本插件;composer 随即在待处理指示器旁显示模型位,`/model` 则以弹窗打开同一份目录。根菜单内,`↑`/`↓` 在模型行、推理滑块和扩展选项间移动。滑块聚焦后,方向键、Home 和 End 用于调整自身档位;Tab 和 Shift+Tab 移至相邻控件。模型搜索框内,方向键移动高亮,Enter 选定。Tab 和 Shift+Tab 在搜索框、清除按钮与高亮模型之间移动,不提交选择;按钮聚焦后用 Enter 或 Space 激活。二级页不显示标题或返回按钮。Escape 返回一级并恢复入口行焦点,再按一次则关闭菜单并聚焦触发器。从模型列表按 Escape 返回或成功选定模型后,焦点回到一级模型行,但不显示灰色底色。随后再次移动鼠标或使用 Tab 导航时,恢复正常的悬停与焦点样式。手机和平板在用户主动点按搜索框或使用键盘导航前,不聚焦搜索框。模型或提供方被删除时(包括账号退登),保留已保存的路由与推理强度,但不展示其 ID;目录条目恢复后重新显示名称与强度。 -鼠标选择沿用浏览器原生点击及其取消行为;仅按下按钮不会选定。打开根菜单时聚焦触发按钮,再次点击触发按钮会关闭菜单并把焦点还给它。根菜单行和搜索清除按钮的键盘焦点与悬停使用相同底色,不显示原生焦点轮廓。选定模型或推理等级后,焦点返回触发按钮但不显示焦点环;焦点离开按钮或重新打开菜单后恢复正常焦点提示。等待任一入口发起的选择结果时,焦点停在触发按钮,触发按钮以加载图标代替下拉箭头,该选择包含的值所在行以加载图标代替勾选标记;选择被拒绝后菜单保持打开。显示模型搜索框时,Tab 返回搜索框并高亮当前模型,否则返回当前选中行。 +鼠标选择沿用浏览器原生点击及其取消行为;仅按下按钮不会选定。打开根菜单时聚焦触发按钮,再次点击该按钮会关闭菜单。选定模型后回到一级菜单并聚焦模型行;调整推理等级后保持菜单打开和滑块焦点。等待模型选择结果时,触发器和模型列表待选行显示加载图标。选择保存期间保留目标值,阻止重复提交,但不显示加载鼠标;推理等级保存期间也保留滑块焦点。选择失败后保留菜单及原选择,允许重试。设置二级页保留原生 Tab 焦点遍历。 ### 模型与推理强度 -按钮模型菜单仅在完整目录超过四个模型时显示搜索框;较小目录直接支持键盘导航,并在所有设备上聚焦当前模型或首个可用行。`/model` 命令始终保留搜索框。两个搜索框均按模型名称进行不区分大小写的匹配,支持按顺序输入不连续字符,并忽略首尾空格。每个提供方内的结果优先按前缀匹配、其次按匹配得分、最后按目录顺序排列。没有匹配项的分组会隐藏。空目录和无匹配结果均通过状态区域通知屏幕阅读器。方向键在各提供方分组的结果间循环移动高亮,焦点保留在搜索框;Enter 或 Tab 选定高亮项。左右方向键仍用于移动输入光标。打开时高亮当前模型或首个可用选项,修改搜索内容后高亮首个结果。重新打开模型面板会清空搜索内容。 +按钮模型菜单仅在完整目录超过四个模型时显示搜索框;较小目录直接支持键盘导航,并在所有设备上聚焦当前模型或首个可用行。`/model` 命令始终保留搜索框。两个搜索框均按模型名称进行不区分大小写的匹配,支持按顺序输入不连续字符,并忽略首尾空格。每个提供方内的结果优先按前缀匹配、其次按匹配得分、最后按目录顺序排列。没有匹配项的分组会隐藏。空目录和无匹配结果均通过状态区域通知屏幕阅读器。方向键在各提供方分组的结果间循环移动高亮,焦点保留在搜索框。composer 菜单用 Enter 选定高亮项,Tab 只移动焦点而不选定;`/model` 弹窗保留命令菜单的键盘行为。左右方向键仍用于移动输入光标。打开时高亮当前模型或首个可用选项,修改搜索内容后高亮首个结果。重新打开模型面板会清空搜索内容。 -composer 菜单中的模型名称和推理等级均使用 400(regular)字重,包括选中项。搜索框沿用 command 弹窗的紧凑样式,在浅/深色主题下均保持背景和边框透明,不显示前置图标,占位文字使用 caption 色。主指针精度较低的设备使用 16px 搜索文字,避免 Safari 聚焦缩放;精细指针设备保留 12px。搜索内容非空时显示清除按钮;点击后恢复完整列表,并将焦点留在搜索框。 +composer 菜单中的模型名称使用 400(regular)字重;当前推理等级标签使用 500 字重。搜索框沿用 command 弹窗的紧凑样式,在浅/深色主题下均保持背景和边框透明,不显示前置图标,占位文字使用 caption 色。主指针精度较低的设备使用 16px 搜索文字,避免 Safari 聚焦缩放;精细指针设备保留 12px。搜索内容非空时显示清除按钮;点击后恢复完整列表,并将焦点留在搜索框。 -两个入口均按提供方分组,DeepSeek 账号排第一,DeepSeek 排第二,第三方提供方保持目录原有顺序。两者采用 [ui-primitives](../ui-primitives/README.zh.md#understand-the-implementation) 异步观察的共享吸顶标题:原位透明,仅吸顶时使用主题的 94% 不透明填充,macOS 桌面端以外使用 `md` 圆角。composer 菜单只显示模型与推理强度名称。导航箭头使用 `--dsw-alias-menu-icon` 文本色。`/model` 弹窗以提供方名称作为分组标题、模型名称作为选项行,不在每行重复提供方,也不显示目录说明。搜索占位文字、无匹配提示和空目录提示与 composer 模型菜单共用同一组本地化文案。弹窗应用所选模型的默认推理强度;composer 随后可以选择任一已公布的推理强度。适配器没有推理元数据时不显示 Effort 行;不存在任意推理强度输入。 +两个入口均按提供方分组,DeepSeek 账号排第一,DeepSeek 排第二,第三方提供方保持目录原有顺序。两者采用 [ui-primitives](../ui-primitives/README.zh.md#understand-the-implementation) 异步观察的共享吸顶标题:原位透明,仅吸顶时使用主题的 94% 不透明填充,macOS 桌面端以外使用 `md` 圆角。composer 菜单只显示模型与推理强度名称。导航箭头使用 `--dsw-alias-menu-icon` 文本色。`/model` 弹窗以提供方名称作为分组标题、模型名称作为选项行,不在每行重复提供方,也不显示目录说明。搜索占位文字、无匹配提示和空目录提示与 composer 模型菜单共用同一组本地化文案。弹窗应用所选模型的默认推理强度;composer 随后可以选择任一已公布的推理强度。适配器没有推理元数据时不显示推理滑块;不存在任意推理强度输入。 展开的控件无法排在同一行时,composer 将模型与推理强度文字替换为模型图标;空间足够后恢复文字。触发器的无障碍名称、提示和菜单仍提供完整选择。 +260px 宽的一级菜单将模型名放在上方,下方显示居中的推理等级标签与原生滑块,滑块以离散刻度表示当前模型公布的有序推理选项。标签使用默认鼠标指针,文字不可选中;悬停仍显示本地化的“推理等级:{effort}”提示,不增加 Tab 焦点。拖动时只在本地预览,松手后提交一次;键盘调整在松键时提交。调整过程中按 Escape 取消预览,切换模型会丢弃尚未结束的手势。仅当适配器未配置默认强度时出现 `Default` 刻度,它不提交显式强度,也不承诺提供方会使用固定档位。只有一个支持档位时仍可阅读,但不能拖动。此处不输入任意 token 预算。 + ### 模型名称扩展 `conversation.input.model.label` 是会话作用域的内联 `single` slot,覆盖 composer 触发按钮(`placement: 'trigger'`)、根菜单中的当前值(`'menu'`)和各模型选项(`'option'`)。owner props 提供 `provider: { id, name }`、准确的目录 `model`、`placement` 和 `selected`。提供方名称是本地化显示名称;按 `provider.id` 匹配渠道,按提供方与模型 ID 的组合识别模型。slot 不接收连接 URL 或凭据。 @@ -61,18 +63,18 @@ composer 菜单中的模型名称和推理等级均使用 400(regular)字重 当会话被其他写句柄占用时,模型选择失败提示用户退出其他正在运行的 DSH 后重试。 -会话级列表 slot `conversation.input.model.options` 在模型与推理等级选项下方追加控件。Owner props 提供 `locked`、`reportFailure(message)` 和 `dismiss()`,后者关闭菜单并同步聚焦触发按钮,供贡献方随后打开其他浮层;贡献方读取自身投影并提供专用命令。启用的开关按钮参与菜单键盘导航。 +会话级列表 slot `conversation.input.model.options` 在模型与推理控件下方追加一级选项。Owner props 提供 `locked`、`reportFailure(message)`、`dismiss()` 和 `openPage({ key, title })`。一级选项在按钮上设置与注册 key 相同的 `data-model-menu-page`,并打开会话作用域 keyed slot `conversation.input.model.page` 中的对应 key。菜单 owner 负责滚动、Escape 导航、焦点返回,以及由 `title` 提供的页面无障碍名称,不显示标题或返回按钮;二级页接收 `locked`、`reportFailure` 与 `dismiss`,所属插件保留全部设置与确认业务逻辑。`dismiss()` 关闭整个菜单并聚焦触发按钮,随后可打开其他浮层。 ----- ## 理解实现 -菜单采用共享 `MenuSurface` 材质,包括用于背景模糊的 macOS 底层;自定义内容遵循[菜单规则](../../../docs/web-styling.zh.md#component-rules)。composer 菜单通过 body portal 使用 fixed 定位及 CSS Anchor Positioning,要求浏览器支持 `anchor-name`、`position-anchor` 和 `anchor()`。触发按钮和菜单共享唯一的锚点名称。CSS 优先将菜单放在按钮上方,右边缘对齐、间距为 8px,并将菜单限制在布局视口的 12px 内边距及桌面窗口边框间距内。桌面页面缩放导致 sticky 输入区重新布局时,面板仍保持与触发器的间距。定位不通过 JavaScript 读取按钮矩形或追踪视口变化。双指缩放时菜单随页面一起缩放,可以超出视觉视口,包括键盘打开时。模型名称超出面板宽度时以省略号截断,角标保持可见。模型与推理等级列表在面板高度限制内纵向滚动。 -
实现细节——点击展开 +菜单采用共享 `MenuSurface` 材质,包括用于背景模糊的 macOS 底层;自定义内容遵循[菜单规则](../../../docs/web-styling.zh.md#component-rules)。composer 菜单通过 body portal 使用 fixed 定位及 CSS Anchor Positioning,要求浏览器支持 `anchor-name`、`position-anchor` 和 `anchor()`。触发按钮和菜单共享唯一的锚点名称。CSS 优先将菜单放在按钮上方,右边缘对齐、间距为 8px,并将菜单限制在布局视口的 12px 内边距及桌面窗口边框间距内。桌面页面缩放导致 sticky 输入区重新布局时,面板仍保持与触发器的间距。定位不通过 JavaScript 读取按钮矩形或追踪视口变化。双指缩放时菜单随页面一起缩放,可以超出视觉视口,包括键盘打开时。模型名称超出面板宽度时以省略号截断,角标保持可见。一级控件、模型列表和设置二级页均在面板高度限制内使用各自的滚动区域。 + composer 的 `ModelSelect` 与 `/model` 选项构建器共用[提供方排序](src/client/provider-order.ts),两个搜索框均在每个提供方内使用 `rankByName`。命令通过 [popupSelect API](../ui-commands/README.zh.md#use-this-package) 提供可选分组与 `searchMode: 'fuzzy-label'`;两个入口均使用 `MenuGroup`,并在渲染分组变化时重建其吸顶观察器。命令弹窗撑满 composer 浮层,按钮则保留紧凑菜单。 两个入口共用一份由 `ModelDirectoryResolver`(`ctx.modelDirectories`)持有的会话级目录:`/model` popupSelect 贡献项(经 `ctx.commandUi` 注册)与 composer 的具名 `conversation.input.model` 位都经 `session.models` 加载会话的可用目录、经 `session.selectModel` 通过同一个 `ModelDirectory` 实例提交,因此任一入口所做的切换正是另一个入口接下来显示的。目录加载与选择共享一个代次计数器,旧响应不会覆盖新结果。目录把最近一次提交的选择发布为 `pending`,直到它完成或被连接重置作废;连接重置丢弃所有常驻投影,并在显示前重新拉取 Host 恢复的选择。目录按会话惰性解析,随会话作用域一并 dispose(资源释放);已寻址 subagent 会话不公开任一入口。每份常驻目录都会直接在转发的 `llm/adapters-updated`、`llm/models-updated`、`settings/document-updated` 与凭据更新事件上重拉。 @@ -110,7 +112,7 @@ composer 的 `ModelSelect` 与 `/model` 选项构建器共用[提供方排序](s - **无创建期或已寻址 subagent 选择**——两个入口都要求既有普通会话的 agent(智能体);没有可纳入会话创建的草稿阶段模型选择,subagent 继续执行也有意不公开独立的模型选择约定。 - **目录名仅供呈现**——选择与持久化使用提供方/模型/推理强度 id;目录查询或确切模型元数据查询失败的提供方以不可选失败行列出,重新加载前保持原样。 -- **不能任意输入推理强度**——composer 仅提供确切模型由适配器公布的推理强度;适配器没有推理元数据时不显示 Effort 行。 +- **不能任意输入推理强度**——composer 仅提供确切模型由适配器公布的推理强度;适配器没有推理元数据时不显示推理滑块。 - **角标只出现在 composer 模型位**——`/model` 弹窗各行、触发按钮的无障碍名称及其提示仍只显示目录名称。 diff --git a/packages/client/ui-model-selection/src/client/EffortSlider.module.css b/packages/client/ui-model-selection/src/client/EffortSlider.module.css new file mode 100644 index 0000000000..645a5f5b61 --- /dev/null +++ b/packages/client/ui-model-selection/src/client/EffortSlider.module.css @@ -0,0 +1,141 @@ +.root { + display: contents; + --effort-thumb-size: 20px; + --effort-track-size: 16px; +} + +.heading { + grid-row: 2; + display: flex; + justify-content: center; + height: 22px; + margin: 10px 14px 0; +} + +.value { + max-width: 100%; + padding: 1px 10px; + border: 1px solid color-mix(in srgb, var(--dsw-alias-state-business-primary) 45%, transparent); + border-radius: 999px; + corner-shape: round; + background: color-mix(in srgb, var(--dsw-alias-state-business-primary) 8%, var(--dsw-alias-bg-module-platform)); + color: var(--dsw-alias-state-business-primary); + font-size: 13px; + line-height: 18px; + font-weight: 500; + text-align: center; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + cursor: default; + -webkit-user-select: none; + user-select: none; +} + +.rail { + grid-row: 3; + position: relative; + margin: 0 8px 2px; +} + +.range { + appearance: none; + display: block; + box-sizing: border-box; + width: 100%; + height: 40px; + margin: 0; + padding: 0; + border: 0; + background: transparent; + cursor: pointer; + touch-action: pan-y; +} + +.range::-webkit-slider-runnable-track { + height: var(--effort-track-size); + border-radius: 999px; + corner-shape: round; + background: + linear-gradient(to right, + color-mix(in srgb, var(--dsw-alias-state-business-primary) 8%, transparent) 0, + color-mix(in srgb, var(--dsw-alias-state-business-primary) 54%, transparent) var(--effort-progress), + color-mix(in srgb, var(--dsw-alias-label-primary) 5%, transparent) var(--effort-progress), + color-mix(in srgb, var(--dsw-alias-label-primary) 5%, transparent) 100%), + color-mix(in srgb, var(--dsw-alias-label-primary) 5%, transparent); +} + +.range::-moz-range-track { + height: var(--effort-track-size); + border-radius: 999px; + corner-shape: round; + background: color-mix(in srgb, var(--dsw-alias-label-primary) 5%, transparent); +} + +.range::-moz-range-progress { + height: var(--effort-track-size); + border-radius: 999px; + corner-shape: round; + background: linear-gradient(to right, + color-mix(in srgb, var(--dsw-alias-state-business-primary) 8%, transparent), + color-mix(in srgb, var(--dsw-alias-state-business-primary) 54%, transparent)); +} + + + +.range::-webkit-slider-thumb { + appearance: none; + width: var(--effort-thumb-size); + height: var(--effort-thumb-size); + margin-top: calc((var(--effort-track-size) - var(--effort-thumb-size)) / 2); + border: 0.5px solid var(--dsw-alias-border-l2); + border-radius: 50%; + corner-shape: round; + background: radial-gradient(circle, var(--dsw-alias-slider-thumb-mark) 0 4px, var(--dsw-alias-slider-thumb) 4.5px); + box-shadow: var(--dsw-elevation-panel); +} + +.range::-moz-range-thumb { + box-sizing: border-box; + width: var(--effort-thumb-size); + height: var(--effort-thumb-size); + border: 0.5px solid var(--dsw-alias-border-l2); + border-radius: 50%; + corner-shape: round; + background: radial-gradient(circle, var(--dsw-alias-slider-thumb-mark) 0 4px, var(--dsw-alias-slider-thumb) 4.5px); + box-shadow: var(--dsw-elevation-panel); +} + +.range:focus-visible { + outline: 2px solid var(--dsw-alias-state-business-primary); + outline-offset: 1px; + border-radius: var(--dsw-radius-sm); +} + +.range:disabled { + opacity: 0.5; + cursor: default; +} + +.ticks { + position: absolute; + inset: 0 calc(var(--effort-thumb-size) / 2); + display: flex; + align-items: center; + justify-content: space-between; + pointer-events: none; +} + +.tick, +.tickActive { + width: 4px; + height: 4px; + border-radius: 50%; + corner-shape: round; + background: var(--dsw-alias-label-caption); + opacity: 0.6; +} + +.ticks [data-current] { + visibility: hidden; +} diff --git a/packages/client/ui-model-selection/src/client/EffortSlider.tsx b/packages/client/ui-model-selection/src/client/EffortSlider.tsx new file mode 100644 index 0000000000..301055506f --- /dev/null +++ b/packages/client/ui-model-selection/src/client/EffortSlider.tsx @@ -0,0 +1,122 @@ +import { useState, type CSSProperties } from 'react' +import { Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' +import css from './EffortSlider.module.css' + +/** One adapter-advertised stop; undefined selects the adapter's default behavior. */ +export interface EffortChoice { + key: string + effort: string | undefined + label: string +} + +/** Data and localized chrome supplied by the model selector. */ +export interface EffortSliderProps { + choices: readonly EffortChoice[] + value: string | undefined + label: string + currentLabel: string + /** Localized tooltip text for the currently displayed effort name. */ + formatTooltip: (effort: string) => string + disabled: boolean + /** A selection is being saved; keep its displayed value and keyboard focus. */ + pending: boolean + onSelect: (effort: string | undefined) => void +} + +type Gesture = { kind: 'pointer' | 'keyboard' | 'cancelled'; source: string; index: number } +const ADJUST_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', 'PageUp', 'PageDown']) + +/** + * Preview a discrete selection locally and submit once when the gesture finishes. + * @param props - Exact-model choices, persisted value, and selection callback. + * @returns A native discrete range with a live value label. + */ +export function EffortSlider({ choices, value, label, currentLabel, formatTooltip, disabled, pending, onSelect }: EffortSliderProps) { + const selectedIndex = choices.findIndex(choice => choice.effort === value) + const source = JSON.stringify([choices.map(choice => [choice.key, choice.effort]), value]) + const [gesture, setGesture] = useState(null) + const preview = gesture?.source === source && gesture.kind !== 'cancelled' ? gesture.index : selectedIndex + const index = Math.max(0, preview) + const current = choices[preview] + const rangeDisabled = disabled || selectedIndex < 0 || choices.length < 2 + const commit = (nextIndex: number): void => { + const choice = choices[nextIndex] + setGesture(null) + if (!disabled && !pending && choice !== undefined) onSelect(choice.effort) + } + const finish = (kind: Gesture['kind'], nextIndex: number): void => { + if (gesture?.kind === kind && gesture.source === source) commit(nextIndex) + else setGesture(null) + } + return ( +
1 ? index / (choices.length - 1) * 100 : 0}%`, + } as CSSProperties} + > +
+ + {current?.label ?? currentLabel} + +
+
+ { + if (pending) { event.preventDefault(); return } + setGesture({ kind: 'pointer', source, index }) + }} + onChange={(event) => { + if (pending || disabled) return + const nextIndex = event.currentTarget.valueAsNumber + if (gesture === null) commit(nextIndex) + else if (gesture.source === source && gesture.kind !== 'cancelled') setGesture({ ...gesture, index: nextIndex }) + }} + onPointerUp={(event) => { finish('pointer', event.currentTarget.valueAsNumber) }} + onPointerCancel={() => { setGesture(null) }} + onLostPointerCapture={() => { setGesture(null) }} + onBlur={() => { setGesture(null) }} + onKeyDown={(event) => { + if (event.nativeEvent.isComposing) return + if (pending && ADJUST_KEYS.has(event.key)) { + event.preventDefault() + event.stopPropagation() + return + } + if (event.key === 'Escape' && gesture !== null) { + event.preventDefault() + event.stopPropagation() + setGesture({ ...gesture, kind: 'cancelled' }) + } else if (ADJUST_KEYS.has(event.key)) { + event.stopPropagation() + if (gesture === null) setGesture({ kind: 'keyboard', source, index }) + } + }} + onKeyUp={(event) => { + if (ADJUST_KEYS.has(event.key)) { + event.stopPropagation() + finish('keyboard', event.currentTarget.valueAsNumber) + } + }} + /> + +
+
+ ) +} 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 9ef7fc2e80..802871af67 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.module.css +++ b/packages/client/ui-model-selection/src/client/ModelSelect.module.css @@ -106,13 +106,14 @@ z-index: 1100; display: flex; flex-direction: column; - /* Rows size the card up to its visible bounds; longer names ellipsize. */ - width: fit-content; + /* Every pane shares one width so drilling in cannot resize the card. */ + width: min(260px, calc(100vw - 24px)); height: fit-content; - min-width: min(240px, calc(100vw - 24px)); - max-width: min(420px, calc(100vw - 24px)); + min-width: 0; + max-width: min(260px, calc(100vw - 24px)); max-height: min(360px, calc(100dvh - 96px)); overflow: hidden; + outline: none; padding: 4px; /* Surface tokens match the Menu primitive card (ui-primitives * Menu.module.css) so every dropdown reads as the same material. */ @@ -129,6 +130,65 @@ --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2); } + + +.rootPage { + display: flex; + flex-direction: column; + min-height: 0; + overflow-y: auto; +} + +.rootPage > * { + flex-shrink: 0; +} + +.reasoningPage { + display: grid; + grid-template-columns: minmax(0, 1fr); +} + +.reasoningPage .modelHeadline { + grid-row: 1; + justify-self: center; + justify-content: center; + width: fit-content; + min-width: 0; + max-width: 100%; + height: 34px; + margin: 4px 0 0; + padding: 0 6px; + gap: 2px; + border-radius: var(--dsw-radius-sm); +} + +.reasoningPage .modelHeadline .cellChevron { + width: 10px; + height: 10px; +} + +.modelHeadline .cellLabel { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); +} + +.modelHeadline .cellValue { + flex: 0 1 auto; + text-align: center; + font-size: 14px; + color: var(--dsw-alias-label-secondary); +} + +.pageBody { + width: 100%; + min-width: 0; + min-height: 0; + overflow-y: auto; +} + .status, .empty { padding: 8px; @@ -362,11 +422,16 @@ } @media (hover: hover) { - .cell:hover { + .cell:hover:not(.modelHeadline), + .reasoningPage .modelHeadline:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); } } +.rootPage .cell[data-return-focus]:is(:hover, :focus-visible) { + background: transparent; +} + .cellLabel { flex: 0 0 auto; white-space: nowrap; diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.tsx b/packages/client/ui-model-selection/src/client/ModelSelect.tsx index 3eea3e37ad..0ae454ffed 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.tsx +++ b/packages/client/ui-model-selection/src/client/ModelSelect.tsx @@ -1,31 +1,6 @@ /** - * ModelSelect: the composer's named model seat (`conversation.input.model`). - * Two-level selection per figma 496:26454's MenuDropdown: the root menu is - * the Model / Effort row pair (label + current value + a right chevron), - * 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. - * Model catalogs above four entries show search, which retains focus while - * ↑/↓ cycle the highlighted result; Enter and Tab accept it. Smaller model - * catalogs, root panes, and effort panes move focus between rows. Escape and Shift+Tab leave a drilled pane first and otherwise close - * back to the trigger. A drilled pane focuses the current effort or model - * search field. Provider headings paint their background only while pinned - * by scrolling. Clearing a query restores the full list and search focus. - * Selecting restores trigger focus without a ring until the trigger loses focus - * or the menu reopens. Mobile devices restore button focus when opening or - * drilling; model search takes focus only after explicit user input. - * Model names match a case-insensitive ordered subsequence - * within each provider group, ranked by - * prefix, alignment score, then catalog order. Returning to the root pane - * hands focus 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. While the directory's pending - * selection is unsettled, the trigger shows a spinner in place of its - * chevron, and each row whose value that selection carries shows one in place - * of its check mark. + * Session model menu with inline reasoning stops and keyed settings pages. + * Model choices and submissions share the same directory as the /model command. */ import { MenuGroup, MenuSurface, observeStickyMenuGroups } from '@deepseek-ai/dsh-client-ui-primitives' import { @@ -36,23 +11,18 @@ import { createPortal } from 'react-dom' import clsx from 'clsx' import type { ModelReasoningEffort, ModelSelection } from '@deepseek-ai/dsh-api-remotes/client' import { - IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconChevronRightOutlineRegular, IconCloseFillRegular, + IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconChevronRightOutlineRegular, + IconCloseFillRegular, IconDataOutlineRegular, IconWarningOutlineRegular, Input, isMobileDevice, rankByName, StateDot, Tag, Toast, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' -import type { ModelLabelOwner, ModelSelectInjected } from './slots.ts' +import type { ModelLabelOwner, ModelMenuPage, ModelSelectInjected } from './slots.ts' +import { EffortSlider, type EffortChoice } from './EffortSlider.tsx' import css from './ModelSelect.module.css' import { orderModelProviders } from './provider-order.ts' -/** Which pane the dropdown shows: the two-row root or one drilled-in list. */ -type Pane = 'root' | 'model' | 'effort' - -/** One dynamic effort row; undefined means preserve the provider default. */ -interface EffortChoice { - key: string - effort: string | undefined - label: string -} +/** The root controls, all models, or a keyed plugin-owned settings page. */ +type Pane = 'root' | 'model' | ModelMenuPage /** * Render the composer model seat. @@ -63,7 +33,7 @@ interface EffortChoice { export function ModelSelect( { locked, available, directory, load, select, resolveText, t, renderSlot }: ModelSelectInjected & Pick, 'locked'> & PropsLocale<'model'> - & Omit, 'SessionProvider'>, + & Omit, 'SessionProvider'>, ) { const state = useSyncExternalStore( fn => directory.subscribe(fn), @@ -74,6 +44,7 @@ export function ModelSelect( const [query, setQuery] = useState('') const [highlightedIndex, setHighlightedIndex] = useState(null) const [selectionFocus, setSelectionFocus] = useState(false) + const [modelReturnFocus, setModelReturnFocus] = useState(false) // The in-menu error strip serves catalog loads (its Retry re-runs the // load); a rejected SELECTION announces through the transient toast // instead, so the strip renders only while the latest failure-capable @@ -176,15 +147,25 @@ export function ModelSelect( // Pane switches unmount the focused row; restore focus inside the menu so // keyboard navigation remains available. - const paneFocus = useRef<'drill' | 'model' | 'effort' | null>(null) + const paneFocus = useRef<'drill' | 'model' | 'effort' | ModelMenuPage | null>(null) const previousShowSearch = useRef(showSearch) useEffect(() => { const changedSearchMode = previousShowSearch.current !== showSearch previousShowSearch.current = showSearch const intent = paneFocus.current ?? (changedSearchMode && pane === 'model' ? 'drill' : null) + if (intent === 'effort' && busy) return paneFocus.current = null if (!open || intent === null) return + if (intent === 'effort') { + menuRef.current?.querySelector('input[type="range"]:not([disabled])')?.focus() + return + } if (intent === 'drill') { + if (typeof pane === 'object') { + const first = menuRef.current?.querySelector('[role="switch"]:not([disabled])') + ;(first ?? menuRef.current ?? triggerRef.current)?.focus() + return + } if (pane === 'model' && showSearch && !isMobileDevice()) { searchRef.current?.focus() return @@ -198,9 +179,11 @@ export function ModelSelect( ;(target ?? triggerRef.current)?.focus() return } - const cell = itemRefs.current[intent === 'effort' ? 1 : 0] + const cell = intent === 'model' ? itemRefs.current[0] + : Array.from(menuRef.current?.querySelectorAll('[data-model-menu-page]') ?? []) + .find(button => button.dataset.modelMenuPage === intent.key) ;(cell !== null && cell !== undefined && !cell.disabled ? cell : triggerRef.current)?.focus() - }, [open, pane, showSearch]) + }, [open, pane, showSearch, selectionFocus, busy]) useEffect(() => { const viewport = groupsRef.current @@ -218,6 +201,7 @@ export function ModelSelect( const show = (): void => { setSelectionFocus(false) + setModelReturnFocus(false) triggerRef.current?.focus() setQuery('') setHighlightedIndex(null) @@ -238,11 +222,6 @@ export function ModelSelect( if (restoreFocus) queueMicrotask(() => { triggerRef.current?.focus() }) } - const closeAfterSelection = (): void => { - setSelectionFocus(true) - close(true) - } - const drill = (next: Pane): void => { setQuery('') setHighlightedIndex(null) @@ -252,13 +231,14 @@ export function ModelSelect( /** Leave a drilled pane for the root one, handing the keyboard back to its cell. */ const back = (from: Exclude): void => { + setModelReturnFocus(from === 'model') paneFocus.current = from setPane('root') } const moveFocus = (offset: number): void => { - const items = Array.from(menuRef.current?.querySelectorAll( - 'button[role="menuitem"]:not([disabled]), button[role="menuitemradio"]:not([disabled]), button[role="switch"]:not([disabled])', + const items = Array.from(menuRef.current?.querySelectorAll( + 'button[role="menuitem"]:not([disabled]), button[role="menuitemradio"]:not([disabled]), button[role="switch"]:not([disabled]), input[type="range"]:not([disabled])', ) ?? []) if (items.length === 0) return const active = items.findIndex(item => item === document.activeElement) @@ -275,63 +255,60 @@ export function ModelSelect( if (event.nativeEvent.isComposing) return if (event.key === 'Escape' && open) { event.preventDefault() + event.stopPropagation() // Escape backs out of a drilled pane first, then closes. - if (pane !== 'root' && currentChoice !== undefined) back(pane) + if (typeof pane === 'object' || (pane === 'model' && currentChoice !== undefined)) back(pane) else close(true) return } if (!open) return - if (pane === 'model' && showSearch && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) { + if (event.key === 'Tab') { + const menu = menuRef.current + const trigger = triggerRef.current + if (menu === null || trigger === null) return + const stops = Array.from(menu.querySelectorAll('button, input, select, textarea, a[href], [tabindex]')) + .filter(item => item.tabIndex >= 0 && !item.matches(':disabled') && item.closest('[hidden], [inert]') === null) + const focused = document.activeElement + if (focused === trigger || focused === menu) { + if (event.shiftKey) { + close() + if (focused === menu) { event.preventDefault(); trigger.focus() } + } else { + event.preventDefault() + ;(stops[0] ?? trigger).focus() + } + return + } + const index = stops.findIndex(item => item === focused) + if (index < 0) return + const next = stops[index + (event.shiftKey ? -1 : 1)] + if (next !== undefined) { + event.preventDefault() + next.focus() + } else { + // Forward Tab continues from the trigger into the composer, not from the body portal. + if (event.shiftKey) event.preventDefault() + close() + trigger.focus() + } + return + } + if (pane === 'model' && showSearch && event.target === searchRef.current + && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) { event.preventDefault() if (!busy && visibleModels.length > 0) { const direction = event.key === 'ArrowDown' ? 1 : -1 setHighlightedIndex((activeModelIndex + direction + visibleModels.length) % visibleModels.length) - searchRef.current?.focus() + searchRef.current.focus() } return } - if (pane === 'model' && showSearch && event.target instanceof HTMLInputElement - && (event.key === 'Enter' || (event.key === 'Tab' && !event.shiftKey))) { - if (event.key === 'Tab' && visibleModels.length === 0) return + if (pane === 'model' && showSearch && event.target === searchRef.current && event.key === 'Enter') { event.preventDefault() const highlighted = visibleModels[activeModelIndex] if (!busy && highlighted !== undefined) choose(highlighted) 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') { - if (event.shiftKey) { - event.preventDefault() - if (pane !== 'root' && currentChoice !== undefined) 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, - // so the keystroke stays unconsumed there. - const focused = document.activeElement - const rows = Array.from(menuRef.current?.querySelectorAll( - 'button[role="menuitem"]:not([disabled]), button[role="menuitemradio"]:not([disabled]), button[role="switch"]:not([disabled])', - ) ?? []) - if (focused instanceof HTMLButtonElement && rows.includes(focused)) { - event.preventDefault() - focused.click() - return - } - if (focused !== triggerRef.current) return - event.preventDefault() - if (pane === 'model' && showSearch) { - setHighlightedIndex(null) - searchRef.current?.focus() - return - } - 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') { event.preventDefault() moveFocus(event.key === 'ArrowDown' ? 1 : -1) @@ -339,6 +316,9 @@ export function ModelSelect( } const onBlur = (event: FocusEvent): void => { + // Non-focusable menu text and native range dragging can temporarily clear DOM focus. + // Outside pointer presses are handled separately; close only for a known outside focus target. + if (event.relatedTarget === null) return if (event.relatedTarget instanceof Node && ( rootRef.current?.contains(event.relatedTarget) === true || menuRef.current?.contains(event.relatedTarget) === true @@ -346,12 +326,17 @@ export function ModelSelect( close() } - const settleSelection = (result: Awaited>): void => { + const settleSelection = (result: Awaited>, origin: 'model' | 'effort'): void => { if (result === undefined) return - if (result.ok) { - if (rootRef.current !== null) closeAfterSelection() - return + if (menuRef.current !== null) { + paneFocus.current = origin + if (result.ok) { + setModelReturnFocus(origin === 'model') + setPane('root') + } + setSelectionFocus(false) } + if (result.ok) return const { error } = result toastSeq.current += 1 setToast({ @@ -362,34 +347,31 @@ export function ModelSelect( }) } - const submit = (selection: ModelSelection): void => { + const submit = (selection: ModelSelection, origin: 'model' | 'effort'): void => { lastActionRef.current = 'select' - // Disabled option rows cannot retain focus while a selection is pending. + // Model rows may unmount; the inline slider keeps focus while its value is saved. setSelectionFocus(true) - triggerRef.current?.focus() - void select(selection).then(settleSelection) + if (origin === 'model') triggerRef.current?.focus() + void select(selection).then((result) => { settleSelection(result, origin) }) } const choose = (selection: ModelSelection): void => { if (state.current?.provider === selection.provider && state.current.model === selection.model) { - closeAfterSelection() + back('model') return } - submit(selection) + submit(selection, 'model') } const chooseEffort = (effort: string | undefined): void => { - if (state.current === null) return - if (effectiveEffort === effort) { - closeAfterSelection() - return - } + if (state.current === null || locked || busy) return + if (effectiveEffort === effort || (effort === undefined && state.current.reasoningEffort === undefined)) return const selection: ModelSelection = { provider: state.current.provider, model: state.current.model, ...effort === undefined ? {} : { reasoningEffort: effort }, } - submit(selection) + submit(selection, 'effort') } const waiting = currentChoice === undefined && state.status === 'loading' @@ -479,38 +461,53 @@ export function ModelSelect( {open && createPortal( {pane === 'root' && ( - <> - - {reasoning !== undefined && ( - + {currentChoice !== undefined && reasoning !== undefined && ( + t('effort.tooltip', { effort })} + disabled={locked} + pending={busy} + onSelect={chooseEffort} + /> )} {renderSlot('conversation.input.model.options', { locked: locked || busy, + openPage: (page) => { drill(page) }, dismiss: () => { close() triggerRef.current?.focus() }, reportFailure: (message) => { setToast({ seq: ++toastSeq.current, text: message }) }, })} - +
)} {pane === 'model' && ( @@ -580,7 +577,7 @@ export function ModelSelect( role="menuitemradio" aria-checked={selected} id={`${id}-model-${index}`} - tabIndex={showSearch ? -1 : 0} + tabIndex={showSearch && index !== activeModelIndex ? -1 : 0} onFocus={() => { setHighlightedIndex(index) }} data-highlighted={index === activeModelIndex ? '' : undefined} className={clsx( @@ -616,41 +613,17 @@ export function ModelSelect( )} - {pane === 'effort' && ( - <> - {state.error !== null && lastActionRef.current === 'load' && ( -
- {t('error.action', { message: state.error })} - -
- )} -
- {effortChoices.length === 0 - ?
{t('empty.efforts')}
- : effortChoices.map(level => ( - - ))} -
- + {typeof pane === 'object' && ( +
+ {renderSlot('conversation.input.model.page', { + locked: locked || busy, + dismiss: () => { + close() + triggerRef.current?.focus() + }, + reportFailure: (message) => { setToast({ seq: ++toastSeq.current, text: message }) }, + }, { entryKey: pane.key })} +
)} , document.body, diff --git a/packages/client/ui-model-selection/src/client/index.ts b/packages/client/ui-model-selection/src/client/index.ts index 224990e848..7a567a4c30 100644 --- a/packages/client/ui-model-selection/src/client/index.ts +++ b/packages/client/ui-model-selection/src/client/index.ts @@ -175,6 +175,7 @@ export function apply(ctx: ClientContext): void { children: { 'conversation.input.model.label': { kind: 'single', scope: 'session', inline: true }, 'conversation.input.model.options': { kind: 'list', scope: 'session' }, + 'conversation.input.model.page': { kind: 'keyed', scope: 'session' }, }, inject: (sessionId): ModelSelectInjected => { const directory = models.directoryFor(sessionId) diff --git a/packages/client/ui-model-selection/src/client/locales.ts b/packages/client/ui-model-selection/src/client/locales.ts index cb2749f9a9..b7b81ff772 100644 --- a/packages/client/ui-model-selection/src/client/locales.ts +++ b/packages/client/ui-model-selection/src/client/locales.ts @@ -10,6 +10,8 @@ /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { + 'effort.tooltip': '推理等级:{effort}', + 'menu.back': '返回', 'provider.account': 'DeepSeek 账号', 'command.label': '模型', 'command.description': '选择本会话使用的模型', @@ -40,6 +42,8 @@ export type ModelKey = keyof typeof zh /** English dictionary, checked complete against the zh key set. */ export const en = { + 'effort.tooltip': 'Reasoning effort: {effort}', + 'menu.back': 'Back', 'provider.account': 'DeepSeek Account', 'command.label': 'Model', 'command.description': 'Select the model for this conversation', @@ -67,6 +71,8 @@ export const en = { /** Japanese copy, checked against the English keys. */ export const ja = { + 'effort.tooltip': '推論強度:{effort}', + 'menu.back': '戻る', 'provider.account': 'DeepSeek アカウント', 'command.label': 'モデル', 'command.description': 'この会話で使用するモデルを選択', @@ -94,6 +100,8 @@ export const ja = { /** Spanish dictionary, checked against the English keys. */ export const es = { + 'effort.tooltip': 'Esfuerzo de razonamiento: {effort}', + 'menu.back': 'Volver', 'provider.account': 'Cuenta DeepSeek', 'command.label': 'modelo', 'command.description': 'Selecciona el modelo para esta conversación', @@ -121,6 +129,8 @@ export const es = { /** French dictionary, checked against the English keys. */ export const fr = { + 'effort.tooltip': 'Effort de raisonnement : {effort}', + 'menu.back': 'Retour', 'provider.account': 'Compte DeepSeek', 'command.label': 'Modèle', 'command.description': 'Sélectionnez le modèle pour cette conversation', @@ -148,6 +158,8 @@ export const fr = { /** German dictionary, checked against the English keys. */ export const de = { + 'effort.tooltip': 'Denkaufwand: {effort}', + 'menu.back': 'Zurück', 'provider.account': 'DeepSeek-Konto', 'command.label': 'Modell', 'command.description': 'Wählen Sie das Modell für dieses Gespräch aus', @@ -175,6 +187,8 @@ export const de = { /** Russian dictionary, checked against the English keys. */ export const ru = { + 'effort.tooltip': 'Уровень рассуждений: {effort}', + 'menu.back': 'Назад', 'provider.account': 'DeepSeek Аккаунт', 'command.label': 'Модель', 'command.description': 'Выберите модель для этого разговора', @@ -202,6 +216,8 @@ export const ru = { /** Portuguese dictionary, checked against the English keys. */ export const pt = { + 'effort.tooltip': 'Esforço de raciocínio: {effort}', + 'menu.back': 'Voltar', 'provider.account': 'DeepSeek Conta', 'command.label': 'Modelo', 'command.description': 'Selecione o modelo para esta conversa', diff --git a/packages/client/ui-model-selection/src/client/slots.ts b/packages/client/ui-model-selection/src/client/slots.ts index 39a31b673f..7e62e9710c 100644 --- a/packages/client/ui-model-selection/src/client/slots.ts +++ b/packages/client/ui-model-selection/src/client/slots.ts @@ -17,21 +17,41 @@ export interface ModelLabelOwner { selected: boolean } +/** A keyed contribution displayed as a second page of the model menu. */ +export interface ModelMenuPage { + /** Registration key in conversation.input.model.page; also marks its root button's data-model-menu-page. */ + key: string + /** Localized accessible name of the detail page. */ + title: string +} + +/** Selection state and feedback shared by menu option entries and detail pages. */ +export interface ModelMenuControls { + /** Whether the composer currently refuses selection changes. */ + locked: boolean + /** Close the menu and focus its trigger synchronously before opening another overlay. */ + dismiss: () => void + /** Report a failed selection through the menu owner's persistent toast. */ + reportFailure: (message: string) => void +} + declare module '@deepseek-ai/dsh-client-ui-slots' { interface SlotMap { /** Session options appended after model and reasoning controls in the root menu. */ 'conversation.input.model.options': { kind: 'list' scope: 'session' - owner: { - /** Whether the composer currently refuses selection changes. */ - locked: boolean - /** Close the menu and focus its trigger synchronously before opening another overlay. */ - dismiss: () => void - /** Report a failed selection through the menu owner's persistent toast. */ - reportFailure: (message: string) => void + owner: ModelMenuControls & { + /** Open a keyed detail page inside this menu; its root button supplies data-model-menu-page for focus return. */ + openPage: (page: ModelMenuPage) => void } } + /** Plugin-owned content displayed as a model-menu detail page. */ + 'conversation.input.model.page': { + kind: 'keyed' + scope: 'session' + owner: ModelMenuControls + } /** * Non-interactive inline model label; selection controls remain owner-managed. * Without a contribution, the badge precedes the catalog name in the trigger diff --git a/packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx b/packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx new file mode 100644 index 0000000000..5ff0e2bb20 --- /dev/null +++ b/packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx @@ -0,0 +1,214 @@ +// @vitest-environment jsdom +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import { EffortSlider, type EffortSliderProps } from '../src/client/EffortSlider.tsx' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { de, en, es, fr, ja, pt, ru, zh } from '../src/client/locales.ts' + +afterEach(() => { + cleanup() + vi.useRealTimers() + vi.unstubAllGlobals() +}) +const choices = ['off', 'low', 'high', 'max'].map(effort => ({ key: effort, effort, label: effort })) +function props(overrides: Partial = {}): EffortSliderProps { + return { + choices, value: 'high', label: 'Effort', currentLabel: 'high', disabled: false, pending: false, + formatTooltip: effort => `Reasoning effort: ${effort}`, onSelect: vi.fn(), ...overrides, + } +} +function range(): HTMLInputElement { + return screen.getByRole('slider') as HTMLInputElement +} + +it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }))('localizes the tag tooltip (%s)', (_locale, dictionary) => { + vi.useFakeTimers() + vi.stubGlobal('matchMedia', (query: string) => ({ + matches: query === '(hover: hover)' || query === '(any-hover: hover)', media: query, onchange: null, + addEventListener: vi.fn(), removeEventListener: vi.fn(), addListener: vi.fn(), removeListener: vi.fn(), dispatchEvent: () => true, + })) + vi.stubGlobal('ResizeObserver', class { + observe() {} + unobserve() {} + disconnect() {} + }) + const t = makeTranslate(dictionary) + const inputProps = props({ + choices: [{ key: 'default', effort: undefined, label: 'Default' }, { key: 'high', effort: 'high', label: 'High' }], + formatTooltip: effort => t('effort.tooltip', { effort }), + }) + const view = render() + const tag = screen.getByText('High') + expect(tag.tabIndex).toBe(-1) + fireEvent.pointerEnter(tag, { pointerType: 'mouse' }) + act(() => { vi.advanceTimersByTime(500) }) + const tooltip = screen.getByRole('tooltip', { hidden: true }) + expect(tooltip.textContent).toBe(dictionary['effort.tooltip'].replace('{effort}', 'High')) + view.rerender() + expect(tooltip.textContent).toBe(dictionary['effort.tooltip'].replace('{effort}', 'Default')) + expect(inputProps.onSelect).not.toHaveBeenCalled() +}) + +it('shows exact advertised stops and the selected value', () => { + render() + expect(range().max).toBe('3') + expect(range().value).toBe('2') + expect(range().getAttribute('aria-valuetext')).toBe('high') + expect(range().min).toBe('0') + expect(range().step).toBe('1') + expect(screen.getByText('high').tabIndex).toBe(-1) + expect(screen.queryByRole('button')).toBeNull() +}) + +it('previews a drag but submits only its final stop on release', () => { + const inputProps = props() + render() + const input = range() + fireEvent.pointerDown(input, { pointerId: 1 }) + fireEvent.change(input, { target: { value: '1' } }) + fireEvent.change(input, { target: { value: '3' } }) + expect(input.getAttribute('aria-valuetext')).toBe('max') + expect(inputProps.onSelect).not.toHaveBeenCalled() + fireEvent.pointerUp(input, { pointerId: 1 }) + expect(inputProps.onSelect).toHaveBeenCalledExactlyOnceWith('max') +}) + +it.each(['pointerCancel', 'lostPointerCapture', 'blur'] as const)('cancels a drag on %s', (event) => { + const inputProps = props() + render() + const input = range() + fireEvent.pointerDown(input) + fireEvent.change(input, { target: { value: '3' } }) + fireEvent[event](input) + fireEvent.pointerUp(input) + expect(inputProps.onSelect).not.toHaveBeenCalled() + expect(input.value).toBe('2') +}) + +it('Escape discards the drag and ignores further movement until release', () => { + const inputProps = props() + const parentKey = vi.fn() + render(
) + const input = range() + fireEvent.pointerDown(input) + fireEvent.change(input, { target: { value: '3' } }) + fireEvent.keyDown(input, { key: 'Escape' }) + fireEvent.change(input, { target: { value: '0' } }) + fireEvent.pointerUp(input) + expect(inputProps.onSelect).not.toHaveBeenCalled() + expect(parentKey).not.toHaveBeenCalled() + expect(input.value).toBe('2') +}) + +it('commits keyboard changes on key release without forwarding adjustment keys', () => { + const inputProps = props() + const parentKey = vi.fn() + render(
) + const input = range() + fireEvent.keyDown(input, { key: 'ArrowLeft' }) + fireEvent.change(input, { target: { value: '1' } }) + fireEvent.keyDown(input, { key: 'ArrowLeft', repeat: true }) + fireEvent.change(input, { target: { value: '0' } }) + expect(inputProps.onSelect).not.toHaveBeenCalled() + fireEvent.keyUp(input, { key: 'ArrowLeft' }) + expect(inputProps.onSelect).toHaveBeenCalledExactlyOnceWith('off') + expect(parentKey).not.toHaveBeenCalled() +}) + +it('lets Tab and an idle Escape reach the owning menu', () => { + const parentKey = vi.fn() + render(
) + fireEvent.keyDown(range(), { key: 'Tab' }) + fireEvent.keyDown(range(), { key: 'Escape' }) + fireEvent.keyUp(range(), { key: 'Tab' }) + expect(parentKey).toHaveBeenCalledTimes(2) +}) + +it('handles a direct assistive-technology change without a preceding pointer or keyboard gesture', () => { + const inputProps = props() + render() + fireEvent.change(range(), { target: { value: '1' } }) + expect(inputProps.onSelect).toHaveBeenCalledExactlyOnceWith('low') +}) + +it('keeps Default distinct from Off and submits an absent effort', () => { + const inputProps = props({ choices: [{ key: 'default', effort: undefined, label: 'Default' }, ...choices] }) + render() + expect(range().max).toBe('4') + fireEvent.change(range(), { target: { value: '0' } }) + expect(inputProps.onSelect).toHaveBeenCalledExactlyOnceWith(undefined) +}) + +it('does not submit a gesture started before the persisted selection changes', () => { + const inputProps = props() + const view = render() + const input = range() + fireEvent.pointerDown(input) + fireEvent.change(input, { target: { value: '3' } }) + view.rerender() + fireEvent.pointerUp(input) + expect(inputProps.onSelect).not.toHaveBeenCalled() + expect(input.value).toBe('1') +}) + +it('blocks selection while locked', () => { + const inputProps = props({ disabled: true }) + render() + expect(range().disabled).toBe(true) + fireEvent.change(range(), { target: { value: '3' } }) + expect(inputProps.onSelect).not.toHaveBeenCalled() +}) + +it('does not commit when another selection locks the control during a gesture', () => { + const inputProps = props() + const view = render() + const input = range() + fireEvent.pointerDown(input) + fireEvent.change(input, { target: { value: '3' } }) + view.rerender() + fireEvent.pointerUp(input) + expect(inputProps.onSelect).not.toHaveBeenCalled() +}) + +it('leaves IME composition keys untouched', () => { + const inputProps = props() + const key = vi.fn() + render(
) + fireEvent.keyDown(range(), { key: 'ArrowRight', isComposing: true }) + expect(key).toHaveBeenCalledOnce() + expect(inputProps.onSelect).not.toHaveBeenCalled() +}) + +it('does not pretend an unknown stored effort matches the first supported stop', () => { + render() + expect(range().disabled).toBe(true) + expect(range().getAttribute('aria-valuetext')).toBe('retired') + expect(screen.getByText('retired')).toBeTruthy() + expect(screen.queryByRole('button')).toBeNull() +}) + +it.each([{ levels: [] }, { levels: choices.slice(0, 1) }])('does not offer dragging with fewer than two choices', ({ levels }) => { + render() + expect(range().disabled).toBe(true) + expect(range().max).toBe('0') +}) + +it('keeps the pending target focusable while blocking pointer, keyboard and direct changes', () => { + const inputProps = props({ value: 'max', pending: true }) + render() + const input = range() + input.focus() + expect(input.disabled).toBe(false) + expect(input.getAttribute('aria-disabled')).toBe('true') + expect(input.getAttribute('aria-busy')).toBe('true') + expect(input.value).toBe('3') + expect(input.getAttribute('aria-valuetext')).toBe('max') + expect(fireEvent.pointerDown(input)).toBe(false) + expect(fireEvent.keyDown(input, { key: 'ArrowLeft' })).toBe(false) + fireEvent.change(input, { target: { value: '0' } }) + fireEvent.keyUp(input, { key: 'ArrowLeft' }) + fireEvent.pointerUp(input) + expect(inputProps.onSelect).not.toHaveBeenCalled() + expect(input.value).toBe('3') + expect(document.activeElement).toBe(input) +}) diff --git a/packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx b/packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx new file mode 100644 index 0000000000..7c3ae849d4 --- /dev/null +++ b/packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx @@ -0,0 +1,187 @@ +// @vitest-environment jsdom +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { afterEach, beforeEach, expect, it, onTestFinished, vi } from 'vitest' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { ComponentProps } from 'react' +import type { OwnerOf } from '@deepseek-ai/dsh-client-ui-slots' +import { ModelSelect } from '../src/client/ModelSelect.tsx' +import type { ModelDirectoryState } from '../src/client/directory.ts' +import { en } from '../src/client/locales.ts' + +beforeEach(() => { + const descriptor = Object.getOwnPropertyDescriptor(Element.prototype, 'scrollIntoView') + Object.defineProperty(Element.prototype, 'scrollIntoView', { configurable: true, value: vi.fn() }) + onTestFinished(() => { + if (descriptor === undefined) Reflect.deleteProperty(Element.prototype, 'scrollIntoView') + else Object.defineProperty(Element.prototype, 'scrollIntoView', descriptor) + }) +}) +afterEach(cleanup) + +function setup(count = 2, hasReasoning = true) { + const select = vi.fn(async () => ({ ok: true as const, value: undefined })) + const toggle = vi.fn() + const directory = createSnapshotStore({ + current: { provider: 'sample', model: 'model-1' }, routable: true, + groups: [{ id: 'sample', name: 'Sample', models: Array.from({ length: count }, (_, index) => ({ + id: `model-${index + 1}`, name: `Model ${index + 1}`, + ...hasReasoning ? { reasoning: { efforts: [{ id: 'low', name: 'Low' }, { id: 'high', name: 'High' }], defaultEffort: 'high' } } : {}, + })) }], failures: [], status: 'ready', pending: null, error: null, + }) + const renderSlot: ComponentProps['renderSlot'] = (name, owner: object, options) => { + if (name === 'conversation.input.model.options') { + const controls = owner as OwnerOf<'conversation.input.model.options'> + return <> + + + + } + if (name === 'conversation.input.model.page') return + return options?.fallback ?? null + } + render(<> typeof text === 'string' ? text : text.en} select={select} renderSlot={renderSlot} t={makeTranslate(en)} />) + const trigger = screen.getByRole('button', { name: /^Select model, current/ }) + fireEvent.click(trigger) + const model = () => screen.getByRole('menuitem', { name: /Model.*Model 1/ }) + const team = () => screen.getByRole('menuitem', { name: 'Agent teamwork' }) + return { select, toggle, directory, trigger, model, team } +} +function tab(shiftKey = false) { + const event = new KeyboardEvent('keydown', { key: 'Tab', shiftKey, bubbles: true, cancelable: true }) + fireEvent(document.activeElement!, event) + return event +} + +it('Tab moves from the trigger through root controls without opening a page or selecting a value', () => { + const view = setup() + tab() + expect(document.activeElement).toBe(view.model()) + tab() + expect(document.activeElement).toBe(screen.getByRole('slider', { name: 'Effort' })) + tab() + expect(document.activeElement).toBe(view.team()) + tab(true) + expect(document.activeElement).toBe(screen.getByRole('slider')) + tab(true) + expect(document.activeElement).toBe(view.model()) + expect(screen.queryByRole('menuitemradio')).toBeNull() + expect(screen.queryByRole('switch')).toBeNull() + expect(view.select).not.toHaveBeenCalled() + expect(view.toggle).not.toHaveBeenCalled() +}) + +it('Shift+Tab from the first root control returns to its trigger instead of activating it', () => { + const view = setup() + tab() + expect(tab(true).defaultPrevented).toBe(true) + expect(document.activeElement).toBe(view.trigger) + expect(screen.queryByRole('menu')).toBeNull() + expect(view.select).not.toHaveBeenCalled() +}) + +it('Tab at the final root control closes the portal and leaves native forward traversal enabled', () => { + const view = setup() + view.team().focus() + expect(tab().defaultPrevented).toBe(false) + expect(document.activeElement).toBe(view.trigger) + expect(screen.queryByRole('menu')).toBeNull() + expect(view.toggle).not.toHaveBeenCalled() +}) + +it('skips a reasoning control when the model does not advertise one', () => { + const view = setup(2, false) + tab(); tab() + expect(document.activeElement).toBe(view.team()) + expect(screen.queryByRole('slider')).toBeNull() + expect(view.select).not.toHaveBeenCalled() +}) + +it('Tab and Shift+Tab traverse small model lists without choosing any model', () => { + const view = setup() + fireEvent.click(view.model()) + const rows = screen.getAllByRole('menuitemradio') + expect(screen.queryByRole('button', { name: 'Back' })).toBeNull() + expect(document.activeElement).toBe(rows[0]) + tab() + expect(document.activeElement).toBe(rows[1]) + tab(true) + expect(document.activeElement).toBe(rows[0]) + expect(view.select).not.toHaveBeenCalled() +}) + +it('Tab leaves search without committing; Shift+Tab returns through search to the trigger', () => { + const view = setup(6) + fireEvent.click(view.model()) + const search = screen.getByRole('searchbox') + fireEvent.keyDown(search, { key: 'ArrowDown' }) + tab() + expect(document.activeElement).toBe(screen.getByRole('menuitemradio', { name: 'Model 2' })) + expect(view.select).not.toHaveBeenCalled() + expect(screen.getAllByRole('menuitemradio').filter(row => row.tabIndex === 0)).toHaveLength(1) + tab(true) + expect(document.activeElement).toBe(search) + tab(true) + expect(document.activeElement).toBe(view.trigger) + expect(screen.queryByRole('searchbox')).toBeNull() +}) + +it('includes the search clear button in Tab order and keeps Space native in search', () => { + const view = setup(6) + fireEvent.click(view.model()) + const search = screen.getByRole('searchbox') + fireEvent.change(search, { target: { value: 'Model 2' } }) + const space = new KeyboardEvent('keydown', { key: ' ', bubbles: true, cancelable: true }) + fireEvent(search, space) + expect(space.defaultPrevented).toBe(false) + tab() + expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Clear search' })) + tab() + expect(document.activeElement).toBe(screen.getByRole('menuitemradio', { name: 'Model 2' })) + expect(view.select).not.toHaveBeenCalled() +}) + +it('Enter still selects a highlighted search result', async () => { + const view = setup(6) + fireEvent.click(view.model()) + const search = screen.getByRole('searchbox') + fireEvent.change(search, { target: { value: 'Model 2' } }) + await act(async () => { fireEvent.keyDown(search, { key: 'Enter' }) }) + await waitFor(() => { + expect(view.select).toHaveBeenCalledExactlyOnceWith({ provider: 'sample', model: 'model-2' }) + }) +}) + +it.each([2, 6])('returns from %i model choices with Escape, then closes the root with Escape', async (count) => { + const view = setup(count) + fireEvent.click(view.model()) + expect(screen.queryByText('Model', { exact: true })).toBeNull() + expect(screen.queryByRole('button', { name: 'Back' })).toBeNull() + fireEvent.keyDown(document.activeElement!, { key: 'Escape' }) + expect(screen.getByRole('slider')).toBeTruthy() + expect(document.activeElement).toBe(view.model()) + fireEvent.keyDown(document.activeElement!, { key: 'Escape' }) + await waitFor(() => { expect(document.activeElement).toBe(view.trigger) }) + expect(screen.queryByRole('menu')).toBeNull() + expect(view.select).not.toHaveBeenCalled() +}) + +it('Tab leaves the Team page without toggling, while Escape returns to its root entry', () => { + const view = setup() + fireEvent.click(view.team()) + const toggle = screen.getByRole('switch') + expect(screen.getByRole('menu', { name: 'Team settings' })).toBeTruthy() + expect(screen.queryByText('Team settings')).toBeNull() + expect(document.activeElement).toBe(toggle) + expect(screen.queryByRole('button', { name: 'Back' })).toBeNull() + tab(true) + expect(document.activeElement).toBe(view.trigger) + expect(screen.queryByRole('switch')).toBeNull() + expect(view.toggle).not.toHaveBeenCalled() + fireEvent.click(view.trigger) + fireEvent.click(view.team()) + fireEvent.keyDown(screen.getByRole('switch'), { key: 'Escape' }) + expect(screen.queryByRole('switch')).toBeNull() + expect(view.team()).toBe(document.activeElement) +}) 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 7990890cec..af1861f0a8 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 @@ -1,6 +1,6 @@ // @vitest-environment jsdom import * as uiPrimitives from '@deepseek-ai/dsh-client-ui-primitives' -import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { RemoteError, SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' import { SessionId } from '@deepseek-ai/dsh-session/types' @@ -100,6 +100,7 @@ describe('ModelSelect label slot', () => { await runtime.root.declare({ 'conversation.input.model.label': { kind: 'single', scope: 'session', inline: true }, 'conversation.input.model.options': { kind: 'list', scope: 'session' }, + 'conversation.input.model.page': { kind: 'keyed', scope: 'session' }, }, ({ renderSlot, SessionProvider }) => @@ -129,15 +130,14 @@ describe('ModelSelect label slot', () => { expect(external.querySelector('div')).toBeNull() fireEvent.keyDown(screen.getByRole('menuitemradio', { name: 'trusted: Same model' }), { key: 'ArrowDown' }) expect(document.activeElement).toBe(external) - fireEvent.keyDown(external, { key: 'Tab' }) + fireEvent.click(external) await waitFor(() => { expect(screen.getByTestId('trigger-external')).toBeTruthy() }) expect(select).toHaveBeenCalledWith({ provider: 'external', model: 'same-model' }) - await waitFor(() => { expect(document.activeElement).toBe(trigger) }) + await waitFor(() => { expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) }) await act(async () => { await plugin.dispose() }) expect(runtime.slots.entries('conversation.input.model.label')).toHaveLength(0) expect(trigger.textContent).toBe('Same model') expect(trigger.querySelector('[data-provider-id="external"][data-model-id="same-model"]')).toBeTruthy() - fireEvent.click(trigger) fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) expect(screen.getAllByRole('menuitemradio').map(row => row.textContent)).toEqual(['Same model', 'Same model']) }) @@ -226,12 +226,17 @@ describe('ModelSelect reasoning effort', () => { name: '选择模型,当前 DeepSeek-V4-Flash,推理等级 High', }) fireEvent.click(trigger) - fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) - expect(screen.getAllByRole('menuitemradio').map(item => item.textContent)) - .toEqual(['Off', 'High', 'Max']) + const efforts = within(screen.getByRole('group', { name: '推理等级' })) + expect(efforts.queryByRole('button')).toBeNull() + expect(efforts.getByRole('slider').getAttribute('max')).toBe('2') + expect(efforts.getByRole('slider', { name: '推理等级' }).getAttribute('aria-valuetext')).toBe('High') + expect(efforts.getByText('High').tabIndex).toBe(-1) + expect(screen.queryByRole('menuitem', { name: /推理等级/ })).toBeNull() expect(screen.queryByText('Largest budget')).toBeNull() - fireEvent.click(screen.getByRole('menuitemradio', { name: /Max/ })) + const slider = efforts.getByRole('slider') + slider.focus() + fireEvent.change(slider, { target: { value: '2' } }) await waitFor(() => { expect(select).toHaveBeenCalledWith({ provider: 'deepseek-official', @@ -239,7 +244,8 @@ describe('ModelSelect reasoning effort', () => { reasoningEffort: 'max', }) expect(trigger.getAttribute('aria-label')).toBe('选择模型,当前 DeepSeek-V4-Flash,推理等级 Max') - expect(document.activeElement).toBe(trigger) + expect(document.activeElement).toBe(slider) + expect(screen.getByRole('menu')).toBeTruthy() }) }) @@ -268,9 +274,66 @@ describe('ModelSelect reasoning effort', () => { fireEvent.click(screen.getByRole('button', { name: '选择模型,当前 Model,推理等级 Default', })) - fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) - expect(screen.getAllByRole('menuitemradio').map(item => item.textContent)) - .toEqual(['Default', 'Standard']) + const efforts = within(screen.getByRole('group', { name: '推理等级' })) + expect(efforts.queryByRole('button')).toBeNull() + expect(efforts.getByRole('slider').getAttribute('max')).toBe('1') + expect(efforts.getByRole('slider').getAttribute('aria-valuetext')).toBe('Default') + }) + + it('submits the Default stop by omitting effort instead of sending a display label', async () => { + const current = { provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' } + const groups = state().groups.map(group => ({ ...group, models: group.models.map(model => ({ + ...model, reasoning: { efforts: reasoning.efforts }, + })) })) + const select = vi.fn().mockResolvedValue({ ok: true, value: undefined }) + render() + fireEvent.click(screen.getByRole('button', { name: /选择模型/ })) + screen.getByRole('slider').focus() + fireEvent.change(screen.getByRole('slider'), { target: { value: '0' } }) + expect(select).toHaveBeenCalledExactlyOnceWith({ provider: 'deepseek-official', model: 'deepseek-v4-flash' }) + await waitFor(() => { expect(document.activeElement).toBe(screen.getByRole('slider')) }) + expect(screen.getByRole('menu')).toBeTruthy() + }) + + it('submits the final dragged stop once and keeps the committed trigger caption until acceptance', async () => { + const select = vi.fn().mockResolvedValue({ ok: true, value: undefined }) + render() + const trigger = screen.getByRole('button', { name: /选择模型/ }) + fireEvent.click(trigger) + const slider = screen.getByRole('slider', { name: '推理等级' }) + slider.focus() + fireEvent.pointerDown(slider, { pointerId: 1 }) + fireEvent.change(slider, { target: { value: '0' } }) + fireEvent.change(slider, { target: { value: '2' } }) + expect(slider.getAttribute('aria-valuetext')).toBe('Max') + expect(trigger.getAttribute('aria-label')).toBe('选择模型,当前 DeepSeek-V4-Flash,推理等级 High') + expect(select).not.toHaveBeenCalled() + fireEvent.pointerUp(slider, { pointerId: 1 }) + expect(select).toHaveBeenCalledExactlyOnceWith({ provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' }) + await waitFor(() => { expect(document.activeElement).toBe(slider) }) + expect(screen.getByRole('menu')).toBeTruthy() + }) + + it('keeps the committed effort and allows retry after a rejected inline selection', async () => { + const select = vi.fn().mockResolvedValue({ ok: false, error: new RemoteError('session/model-unavailable', 'effort unavailable', { + provider: 'deepseek-official', model: 'deepseek-v4-flash', + }) }) + render() + fireEvent.click(screen.getByRole('button', { name: /选择模型/ })) + screen.getByRole('slider').focus() + fireEvent.change(screen.getByRole('slider'), { target: { value: '2' } }) + expect((await screen.findByRole('alert')).textContent).toContain('effort unavailable') + expect(screen.getByRole('menu')).toBeTruthy() + const slider = screen.getByRole('slider', { name: '推理等级' }) + expect(slider.getAttribute('aria-valuetext')).toBe('High') + expect(slider.hasAttribute('disabled')).toBe(false) + expect(document.activeElement).toBe(slider) + await act(async () => { fireEvent.change(slider, { target: { value: '0' } }) }) + expect(select).toHaveBeenLastCalledWith({ provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'off' }) }) it('opens model choices without exposing a saved route absent from the catalog', () => { @@ -298,7 +361,7 @@ describe('ModelSelect reasoning effort', () => { expect(select).not.toHaveBeenCalled() expect(directory.getSnapshot().current).toEqual({ provider: 'deepseek-official', model: 'removed-model' }) fireEvent.keyDown(screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' }), { key: 'Escape' }) - expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() + expect(screen.queryByRole('group', { name: '模型' })).toBeNull() }) it.each(['model', 'provider'])('hides the saved id and effort when the selected %s disappears', (removed) => { @@ -316,7 +379,7 @@ describe('ModelSelect reasoning effort', () => { fireEvent.click(trigger) expect(screen.getByRole('status').textContent).toBe(zh['empty.models']) fireEvent.keyDown(trigger, { key: 'Tab', shiftKey: true }) - expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() + expect(screen.queryByRole('group', { name: '模型' })).toBeNull() }) it.each([null, state().current])('shows loading until the catalog and Session projection are both ready (%j)', async (current) => { @@ -378,15 +441,17 @@ describe('ModelSelect reasoning effort', () => { fireEvent.mouseMove(rejected) fireEvent.click(rejected) const toast = await screen.findByRole('alert') - expect(document.activeElement).toBe(trigger) + const selected = screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' }) + expect(document.activeElement).toBe(selected) expect(toast.textContent).toBe(sessionInUse ? zh['error.sessionInUse'] : '模型操作失败:session/model-unavailable: session already contains images') // The selection failure does not render the in-menu load strip (no Retry). expect(screen.queryByRole('button', { name: '重试' })).toBeNull() - fireEvent.keyDown(trigger, { key: 'Tab' }) + fireEvent.keyDown(selected, { key: 'Tab' }) expect(screen.queryByRole('searchbox')).toBeNull() - expect(document.activeElement).toBe(screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' })) + expect(document.activeElement).toBe(rejected) + expect(select).toHaveBeenCalledTimes(1) }) it('spins on the trigger and the chosen model row until the selection settles, across pane changes', async () => { @@ -433,21 +498,66 @@ describe('ModelSelect reasoning effort', () => { expect(trigger.getAttribute('aria-busy')).toBe('false') }) - it('spins on the chosen effort row only', () => { + it('announces the pending target while retaining slider focus and blocking duplicate submissions', async () => { const directory = createSnapshotStore(state()) + const pending = Promise.withResolvers<{ ok: true; value: undefined }>() + onTestFinished(async () => { await act(async () => { pending.resolve({ ok: true, value: undefined }) }) }) const select = vi.fn((selection: ModelSelection) => { directory.set(state({ status: 'selecting', pending: selection })) - return new Promise(() => {}) + return pending.promise }) render() - fireEvent.click(screen.getByRole('button', { name: /选择模型|当前/ })) - fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) - fireEvent.click(screen.getByRole('menuitemradio', { name: /Max/ })) - expect(screen.getAllByRole('menuitemradio') - .filter(row => row.querySelector('[data-state="ongoing"]') !== null) - .map(row => row.textContent)).toEqual(['Max']) + const trigger = screen.getByRole('button', { name: /选择模型|当前/ }) + fireEvent.click(trigger) + const slider = screen.getByRole('slider', { name: '推理等级' }) + screen.getByRole('slider').focus() + fireEvent.change(screen.getByRole('slider'), { target: { value: '2' } }) + expect(trigger.getAttribute('aria-busy')).toBe('true') + expect(trigger.querySelector('[data-state="ongoing"]')).not.toBeNull() + expect(slider.hasAttribute('disabled')).toBe(false) + expect(slider.getAttribute('aria-disabled')).toBe('true') + expect(slider.getAttribute('aria-busy')).toBe('true') + expect(slider.getAttribute('aria-valuetext')).toBe('Max') + expect(document.activeElement).toBe(slider) + fireEvent.change(slider, { target: { value: '0' } }) + expect(select).toHaveBeenCalledExactlyOnceWith({ + provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max', + }) + await act(async () => { + directory.set(state({ current: { provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' } })) + pending.resolve({ ok: true, value: undefined }) + }) + expect(screen.getByRole('menu')).toBeTruthy() + expect(trigger.getAttribute('aria-busy')).toBe('false') + expect(slider.getAttribute('aria-disabled')).toBe('false') + expect(slider.getAttribute('aria-valuetext')).toBe('Max') + expect(document.activeElement).toBe(slider) + }) + + it('keeps transient focus loss inside the menu but closes on a known outside focus target', () => { + render(<>) + const trigger = screen.getByRole('button', { name: /选择模型/ }) + fireEvent.click(trigger) + fireEvent.blur(trigger, { relatedTarget: null }) + expect(screen.getByRole('menu')).toBeTruthy() + fireEvent.blur(trigger, { relatedTarget: screen.getByRole('button', { name: 'Outside' }) }) + expect(screen.queryByRole('menu')).toBeNull() + }) + + it('closes the portaled model list when focus moves from search to an outside editor', () => { + render(<>
) + fireEvent.click(screen.getByRole('button', { name: /选择模型/ })) + fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) + expect(document.activeElement).toBe(screen.getByRole('searchbox')) + const editor = screen.getByLabelText('Outside editor') + act(() => { editor.focus() }) + expect(document.activeElement).toBe(editor) + expect(screen.queryByRole('menu')).toBeNull() }) it('anchors the body portal with CSS and closes only on truly-outside mousedown', () => { @@ -541,31 +651,23 @@ describe('ModelSelect keyboard walk', () => { expect(document.activeElement).toBe(trigger) const modelCell = screen.getByRole('menuitem', { name: /^模型/ }) - const effortCell = screen.getByRole('menuitem', { name: /推理等级/ }) + const slider = screen.getByRole('slider', { name: '推理等级' }) fireEvent.keyDown(trigger, { key: 'ArrowDown' }) fireEvent.keyDown(modelCell, { key: 'ArrowDown' }) - expect(document.activeElement).toBe(effortCell) - fireEvent.keyDown(effortCell, { key: 'Tab' }) - const high = screen.getByRole('menuitemradio', { name: 'High' }) - const max = screen.getByRole('menuitemradio', { name: /Max/ }) - expect(document.activeElement).toBe(high) - fireEvent.keyDown(high, { key: 'ArrowDown' }) - expect(document.activeElement).toBe(max) - fireEvent.keyDown(max, { key: 'Escape' }) - - const restoredEffortCell = screen.getByRole('menuitem', { name: /推理等级/ }) - expect(document.activeElement).toBe(restoredEffortCell) - fireEvent.keyDown(restoredEffortCell, { key: 'ArrowUp' }) - const restoredModelCell = screen.getByRole('menuitem', { name: /^模型/ }) - expect(document.activeElement).toBe(restoredModelCell) - fireEvent.keyDown(restoredModelCell, { key: 'Tab' }) + expect(document.activeElement).toBe(slider) + expect(fireEvent.keyDown(slider, { key: 'ArrowDown' })).toBe(true) + expect(document.activeElement).toBe(slider) + expect(screen.queryByRole('searchbox')).toBeNull() + fireEvent.keyDown(slider, { key: 'Tab', shiftKey: true }) + expect(document.activeElement).toBe(modelCell) + fireEvent.click(modelCell) const model = screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' }) expect(document.activeElement).toBe(model) if (modelCount > 4) { const search = screen.getByRole('searchbox') expect(document.activeElement).not.toBe(search) fireEvent.keyDown(model, { key: 'ArrowDown' }) - expect(document.activeElement).toBe(search) + expect(document.activeElement).toBe(screen.getByRole('menuitemradio', { name: 'Model 2' })) } else { expect(screen.queryByRole('searchbox')).toBeNull() } @@ -578,63 +680,69 @@ describe('ModelSelect keyboard walk', () => { }, ) - it.each(['model', 'effort'])('prevents button mousedown defaults in the %s pane without selecting it', (pane) => { + it.each(['model', 'inline effort'])('does not select on button mousedown and mouseup alone in %s controls', (kind) => { const select = mountOpen() - const cell = screen.getByRole('menuitem', { name: pane === 'model' ? /^模型/ : /推理等级/ }) + const cell = screen.getByRole('menuitem', { name: /^模型/ }) expect(fireEvent.mouseDown(cell.firstElementChild!)).toBe(false) - fireEvent.click(cell) - const rows = screen.getAllByRole('menuitemradio') + if (kind === 'model') fireEvent.click(cell) + const target = kind === 'model' + ? screen.getAllByRole('menuitemradio')[0]! + : screen.getByRole('slider') const focused = document.activeElement - expect(fireEvent.mouseDown(rows[0]!.firstElementChild!)).toBe(false) + expect(fireEvent.mouseDown(target)).toBe(kind === 'inline effort') fireEvent.mouseUp(screen.getByRole('menu')) expect(select).not.toHaveBeenCalled() - fireEvent.keyDown(focused!, { key: 'Escape' }) - expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: pane === 'model' ? /^模型/ : /推理等级/ })) + expect(document.activeElement).toBe(focused) + if (kind === 'inline effort') { + expect(fireEvent.mouseDown(screen.getByRole('slider'))).toBe(true) + expect(screen.getByRole('slider').getAttribute('aria-valuetext')).toBe('High') + } else { + fireEvent.keyDown(focused!, { key: 'Escape' }) + expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) + } }) - it('↑↓ walk the rows of the shown pane, wrapping, and stay open', () => { - mountOpen() - // The trigger holds focus while the menu opens: the first forward step - // enters at the first cell instead of skipping it. false = preventDefault ran. - const cells = screen.getAllByRole('menuitem') - expect(fireEvent.keyDown(cells[0]!, { key: 'ArrowDown' })).toBe(false) - expect(document.activeElement).toBe(cells[0]) - - fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) - const rows = screen.getAllByRole('menuitemradio') - expect(rows.map(row => row.textContent)).toEqual(['Off', 'High', 'Max']) - // The pane opens on its checked row, so walking starts from High. - fireEvent.keyDown(rows[1]!, { key: 'ArrowDown' }) - expect(document.activeElement).toBe(rows[2]) - fireEvent.keyDown(rows[2]!, { key: 'ArrowDown' }) // wraps to the top - expect(document.activeElement).toBe(rows[0]) - fireEvent.keyDown(rows[0]!, { key: 'ArrowUp' }) // wraps to the bottom - expect(document.activeElement).toBe(rows[2]) - expect(screen.getByRole('menu')).toBeTruthy() - }) - - it('Tab settles the focused row like Enter and closes the menu', async () => { + it('walks between root controls while leaving adjustment arrows to the native range', () => { const select = mountOpen() - fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) - const rows = screen.getAllByRole('menuitemradio') - fireEvent.keyDown(rows[1]!, { key: 'ArrowDown' }) // High → Max - expect(fireEvent.keyDown(rows[2]!, { key: 'Tab' })).toBe(false) - expect(select).toHaveBeenCalledWith({ + const model = screen.getByRole('menuitem', { name: /^模型/ }) + const slider = screen.getByRole('slider', { name: '推理等级' }) + expect(fireEvent.keyDown(model, { key: 'ArrowDown' })).toBe(false) + expect(document.activeElement).toBe(model) + fireEvent.keyDown(model, { key: 'ArrowDown' }) + expect(document.activeElement).toBe(slider) + expect(fireEvent.keyDown(slider, { key: 'ArrowRight' })).toBe(true) + expect(document.activeElement).toBe(slider) + expect(fireEvent.keyDown(slider, { key: 'Tab', shiftKey: true })).toBe(false) + expect(document.activeElement).toBe(model) + fireEvent.keyDown(model, { key: 'ArrowUp' }) + expect(document.activeElement).toBe(slider) + expect(screen.getByRole('menu')).toBeTruthy() + expect(select).not.toHaveBeenCalled() + }) + + it('commits a range keyboard gesture once with the model route and retains slider focus', async () => { + const select = mountOpen() + const slider = screen.getByRole('slider', { name: '推理等级' }) + slider.focus() + fireEvent.keyDown(slider, { key: 'End' }) + // jsdom does not perform the native range value change for a keyboard event. + fireEvent.change(slider, { target: { value: '2' } }) + expect(slider.getAttribute('aria-valuetext')).toBe('Max') + expect(select).not.toHaveBeenCalled() + fireEvent.keyUp(slider, { key: 'End' }) + expect(select).toHaveBeenCalledExactlyOnceWith({ provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max', }) - await waitFor(() => { expect(screen.queryByRole('menu')).toBeNull() }) + await waitFor(() => { expect(document.activeElement).toBe(slider) }) + expect(screen.getByRole('menu')).toBeTruthy() }) - it('Shift+Tab leaves a drilled pane and then closes, like Escape', () => { + it('Shift+Tab from the first model closes the menu and returns to the trigger', () => { mountOpen() - fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) - const rows = screen.getAllByRole('menuitemradio') - expect(fireEvent.keyDown(rows[0]!, { key: 'Tab', shiftKey: true })).toBe(false) - // Back on the drilled cell, then closed on the second press. - const cells = screen.getAllByRole('menuitem') - expect(document.activeElement).toBe(cells[1]) - expect(screen.getByRole('menu')).toBeTruthy() - fireEvent.keyDown(cells[1]!, { key: 'Tab', shiftKey: true }) + fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) + const selected = screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' }) + expect(fireEvent.keyDown(selected, { key: 'Tab', shiftKey: true })).toBe(false) + expect(document.activeElement).toBe(screen.getByRole('button', { name: /选择模型/ })) expect(screen.queryByRole('menu')).toBeNull() }) @@ -658,26 +766,30 @@ describe('ModelSelect keyboard walk', () => { it('a backward step from outside the list enters at the last row, and a closed menu leaves Tab native', () => { mountOpen() - const [modelRow, effortRow] = screen.getAllByRole('menuitem') - expect(fireEvent.keyDown(modelRow!, { key: 'ArrowUp' })).toBe(false) - expect(document.activeElement).toBe(effortRow) + const modelRow = screen.getByRole('menuitem', { name: /^模型/ }) + const slider = screen.getByRole('slider', { name: '推理等级' }) + expect(fireEvent.keyDown(modelRow, { key: 'ArrowUp' })).toBe(false) + expect(document.activeElement).toBe(slider) const trigger = screen.getByRole('button', { name: /选择模型/ }) fireEvent.keyDown(trigger, { key: 'Escape' }) expect(screen.queryByRole('menu')).toBeNull() expect(fireEvent.keyDown(trigger, { key: 'Tab' })).toBe(true) }) - it('hands a drilled pane the focus its unmounted cell left behind, on the value in use', () => { - mountOpen() - fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) - const rows = screen.getAllByRole('menuitemradio') - // The fixture's model defaults to the High effort: the checked row is where - // the keyboard lands, not the top of the list. - expect(rows[1]!.getAttribute('aria-checked')).toBe('true') - expect(document.activeElement).toBe(rows[1]) - // The walk continues from there. - fireEvent.keyDown(rows[1]!, { key: 'ArrowDown' }) - expect(document.activeElement).toBe(rows[2]) + it('returns from all models to the committed effort without submitting another selection', () => { + const select = vi.fn() + render() + fireEvent.click(screen.getByRole('button', { name: /选择模型/ })) + expect(screen.getByRole('slider').getAttribute('aria-valuetext')).toBe('Max') + fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) + expect(screen.queryByRole('slider')).toBeNull() + fireEvent.keyDown(document.activeElement!, { key: 'Escape' }) + expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) + expect(screen.getByRole('slider').getAttribute('aria-valuetext')).toBe('Max') + expect(screen.queryByRole('button', { name: 'Max' })).toBeNull() + expect(select).not.toHaveBeenCalled() }) it('keeps the card navigable when a pane has no rows, and leaves a retry its Tab', () => { @@ -702,12 +814,12 @@ describe('ModelSelect keyboard walk', () => { expect(fireEvent.mouseDown(retry)).toBe(false) fireEvent.click(retry) expect(load).toHaveBeenCalledTimes(2) - expect(screen.getByRole('group', { name: '模型与推理等级' })).toBeTruthy() + expect(screen.getByRole('group', { name: '模型' })).toBeTruthy() retry.focus() // A control that is not a row keeps the browser's traversal. expect(fireEvent.keyDown(retry, { key: 'Tab' })).toBe(true) fireEvent.keyDown(retry, { key: 'Escape' }) - expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() + expect(screen.queryByRole('group', { name: '模型' })).toBeNull() }) it('focuses the checked model in a small catalog', () => { @@ -719,19 +831,15 @@ describe('ModelSelect keyboard walk', () => { expect(document.activeElement).toBe(rows[0]) }) - it('Escape returns to the root pane with the keyboard on the cell that drilled in', () => { - mountOpen() - fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) - const rows = screen.getAllByRole('menuitemradio') - fireEvent.keyDown(rows[0]!, { key: 'Escape' }) - // The root pane is back with its two cells. - const cells = screen.getAllByRole('menuitem') - // Back on the drilled cell, so the next keystroke still reaches the menu. - expect(document.activeElement).toBe(cells[1]) - expect(screen.getByRole('menu')).toBeTruthy() - // A second Escape closes back to the trigger. - fireEvent.keyDown(cells[1]!, { key: 'Escape' }) + it('Escape from an unchanged inline slider closes the root menu and restores trigger focus', async () => { + const select = mountOpen() + const trigger = screen.getByRole('button', { name: /选择模型/ }) + const slider = screen.getByRole('slider', { name: '推理等级' }) + slider.focus() + expect(fireEvent.keyDown(slider, { key: 'Escape' })).toBe(false) expect(screen.queryByRole('menu')).toBeNull() + await waitFor(() => { expect(document.activeElement).toBe(trigger) }) + expect(select).not.toHaveBeenCalled() }) it('Escape from the model list lands back on the model cell', () => { @@ -776,7 +884,7 @@ describe('ModelSelect catalog size', () => { expect(search).toBeInstanceOf(HTMLInputElement) expect(document.activeElement).toBe(search) expect(search.getAttribute('aria-activedescendant')).toBe(rows[1]!.id) - expect(rows.every(row => row.tabIndex === -1)).toBe(true) + expect(rows.filter(row => row.tabIndex === 0)).toEqual([rows[1]]) } else { expect(screen.queryByRole('searchbox')).toBeNull() expect(document.activeElement).toBe(count === 0 ? trigger : rows[count > 1 ? 1 : 0]) @@ -827,7 +935,7 @@ describe('ModelSelect catalog size', () => { .toBe(screen.getAllByRole('menuitemradio')[checked ? 2 : 0]!.id) }) - it('moves actual row focus with arrows, leaves Enter native, and selects with Tab in a small catalog', async () => { + it('moves actual row focus with arrows and Tab without choosing, then activates a small-catalog row', async () => { const select = vi.fn().mockResolvedValue({ ok: true, value: undefined }) render( { expect(document.activeElement).toBe(rows[2]) expect(select).not.toHaveBeenCalled() expect(fireEvent.keyDown(rows[2]!, { key: 'Tab' })).toBe(false) - expect(select).toHaveBeenCalledWith({ provider: 'deepseek-official', model: 'model-3' }) - await waitFor(() => { expect(document.activeElement).toBe(trigger) }) - expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() - expect(trigger.hasAttribute('data-selection-focus')).toBe(true) + expect(document.activeElement).toBe(rows[3]) + expect(select).not.toHaveBeenCalled() + fireEvent.click(rows[3]!) + expect(select).toHaveBeenCalledWith({ provider: 'deepseek-official', model: 'model-4' }) + await waitFor(() => { expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) }) + expect(screen.queryByRole('menuitemradio')).toBeNull() + expect(screen.getByRole('menu')).toBeTruthy() }) - it('keeps Tab selection available after hovering a small-catalog row', async () => { + it('moves Tab focus without selecting after hovering a small-catalog row', () => { const select = vi.fn().mockResolvedValue({ ok: true, value: undefined }) render() @@ -870,8 +981,8 @@ describe('ModelSelect catalog size', () => { expect(document.activeElement).toBe(row) expect(row.hasAttribute('data-highlighted')).toBe(true) expect(fireEvent.keyDown(row, { key: 'Tab' })).toBe(false) - expect(select).toHaveBeenCalledWith({ provider: 'deepseek-official', model: 'model-3' }) - await waitFor(() => { expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() }) + expect(document.activeElement).toBe(screen.getByRole('menuitemradio', { name: 'Model 4' })) + expect(select).not.toHaveBeenCalled() }) it.each(['Escape', 'Tab'])('leaves a small model pane with %s and returns to its root cell', (key) => { @@ -882,10 +993,14 @@ describe('ModelSelect catalog size', () => { fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) const row = screen.getAllByRole('menuitemradio')[0]! expect(fireEvent.keyDown(row, { key, shiftKey: key === 'Tab' })).toBe(false) - const cell = screen.getByRole('menuitem', { name: /^模型/ }) - expect(document.activeElement).toBe(cell) expect(select).not.toHaveBeenCalled() - fireEvent.keyDown(cell, { key, shiftKey: key === 'Tab' }) + if (key === 'Escape') { + const cell = screen.getByRole('menuitem', { name: /^模型/ }) + expect(document.activeElement).toBe(cell) + fireEvent.keyDown(cell, { key }) + } else { + expect(document.activeElement).toBe(screen.getByRole('button', { name: /选择模型/ })) + } expect(screen.queryByRole('menu')).toBeNull() }) }) @@ -901,7 +1016,7 @@ describe('ModelSelect search', () => { expect(document.activeElement).toBe(search) fireEvent.change(search, { target: { value: 'zzzz' } }) fireEvent.keyDown(search, { key: 'Escape' }) - expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() + expect(screen.queryByRole('group', { name: '模型' })).toBeNull() fireEvent.click(trigger) expect(screen.getByRole('searchbox').getAttribute('value')).toBe('') expect(document.activeElement).toBe(screen.getByRole('searchbox')) @@ -922,7 +1037,7 @@ describe('ModelSelect search', () => { expect(screen.getByRole('status').closest('[role="menu"]')).toBeNull() }) - it.each(['Enter', 'Tab'])('returns focus silently after %s accepts the current model, without suppressing later focus', async (key) => { + it('returns to the root model after Enter accepts the current model, without suppressing later focus', async () => { const select = vi.fn() render(<> @@ -932,9 +1047,9 @@ describe('ModelSelect search', () => { const trigger = screen.getByRole('button', { name: /选择模型/ }) fireEvent.click(trigger) fireEvent.click(screen.getByRole('menuitem', { name: /模型/ })) - fireEvent.keyDown(screen.getByRole('searchbox'), { key }) - await waitFor(() => { expect(document.activeElement).toBe(trigger) }) - expect(trigger.hasAttribute('data-selection-focus')).toBe(true) + fireEvent.keyDown(screen.getByRole('searchbox'), { key: 'Enter' }) + await waitFor(() => { expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) }) + expect(trigger.hasAttribute('data-selection-focus')).toBe(false) expect(select).not.toHaveBeenCalled() act(() => { screen.getByRole('button', { name: 'Outside' }).focus() }) expect(trigger.hasAttribute('data-selection-focus')).toBe(false) @@ -942,7 +1057,7 @@ describe('ModelSelect search', () => { expect(trigger.hasAttribute('data-selection-focus')).toBe(false) }) - it.each(['Enter', 'Tab'])('keeps typing focus while arrows wrap across groups and %s accepts the highlight', async (key) => { + it('keeps typing focus while arrows wrap across groups and Enter accepts the highlight', async () => { const select = vi.fn().mockResolvedValue({ ok: true, value: undefined }) const directory = createSnapshotStore(state({ current: { provider: 'deepseek-official', model: 'beta' }, @@ -985,19 +1100,19 @@ describe('ModelSelect search', () => { expect(search.hasAttribute('aria-activedescendant')).toBe(false) fireEvent.keyDown(search, { key: 'Enter' }) expect(select).not.toHaveBeenCalled() - expect(fireEvent.keyDown(search, { key: 'Tab' })).toBe(true) + expect(fireEvent.keyDown(search, { key: 'Tab' })).toBe(false) + expect(document.activeElement).toBe(screen.getByRole('button', { name: '清除搜索' })) fireEvent.click(screen.getByRole('button', { name: '清除搜索' })) const restored = screen.getAllByRole('menuitemradio') expect(search.getAttribute('aria-activedescendant')).toBe(restored[0]!.id) fireEvent.mouseMove(restored[4]!) expect(search.getAttribute('aria-activedescendant')).toBe(restored[4]!.id) expect(document.activeElement).toBe(search) - fireEvent.keyDown(search, { key }) + fireEvent.keyDown(search, { key: 'Enter' }) expect(select).toHaveBeenCalledWith({ provider: 'other', model: 'gamma' }) - await waitFor(() => { expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() }) - const trigger = screen.getByRole('button', { name: /选择模型/ }) - await waitFor(() => { expect(document.activeElement).toBe(trigger) }) - expect(trigger.hasAttribute('data-selection-focus')).toBe(true) + await waitFor(() => { expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) }) + expect(screen.queryByRole('menuitemradio')).toBeNull() + expect(screen.getByRole('menu')).toBeTruthy() }) it('filters model names fuzzily, hides empty groups, clears on reopening, and selects a result', async () => { @@ -1045,8 +1160,8 @@ describe('ModelSelect search', () => { fireEvent.keyDown(reopened, { key: 'ArrowDown' }) expect(document.activeElement).toBe(reopened) expect(reopened.getAttribute('aria-activedescendant')).toBe(row.id) - fireEvent.keyDown(reopened, { key: 'Tab' }) - await waitFor(() => { expect(screen.queryByRole('menu')).toBeNull() }) + fireEvent.keyDown(reopened, { key: 'Enter' }) + await waitFor(() => { expect(screen.queryByRole('menuitemradio')).toBeNull() }) expect(select).toHaveBeenCalledWith({ provider: 'other', model: 'gemini' }) }) }) @@ -1066,7 +1181,7 @@ it('hides the inherited effort until a listed model is selected', async () => { const row = screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' }) expect(document.activeElement).toBe(row) fireEvent.keyDown(row, { key: 'Escape' }) - expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() + expect(screen.queryByRole('group', { name: '模型' })).toBeNull() fireEvent.click(trigger) expect(screen.queryByRole('searchbox')).toBeNull() expect(document.activeElement).toBe(screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' })) @@ -1120,6 +1235,117 @@ it('restores the account model name after login without changing the saved route }) +describe('ModelSelect contributed pages', () => { + function mountPage(locked = false, withSwitch = true) { + const toggle = vi.fn() + const select = vi.fn() + const renderSlot: ComponentProps['renderSlot'] = (name, owner: object, options) => { + if (name === 'conversation.input.model.options') { + const controls = owner as OwnerOf<'conversation.input.model.options'> + return + } + if (name === 'conversation.input.model.page') { + if (options?.entryKey !== 'fixture-settings') throw new Error('Unexpected detail page key') + const controls = owner as OwnerOf<'conversation.input.model.page'> + return <> +

用于解释该设置的完整说明

+ {withSwitch && } + + + + } + return options?.fallback ?? null + } + const directory = createSnapshotStore(state()) + const view = render() + const trigger = screen.getByRole('button', { name: /^选择模型/ }) + if (!locked) fireEvent.click(trigger) + return { directory, view, trigger, renderSlot, toggle, select } + } + + it('opens only the keyed detail controls and returns to the invoking entry with Escape', () => { + const { toggle, select } = mountPage() + expect(screen.queryByRole('switch')).toBeNull() + expect(screen.queryByText('用于解释该设置的完整说明')).toBeNull() + const entry = screen.getByRole('menuitem', { name: '设置 关' }) + fireEvent.click(entry) + const toggleButton = screen.getByRole('switch', { name: '启用示例设置' }) + expect(document.activeElement).toBe(toggleButton) + expect(screen.queryByText('示例设置')).toBeNull() + expect(screen.getByRole('menu', { name: '示例设置' })).toBeTruthy() + expect(screen.queryByRole('button', { name: '返回' })).toBeNull() + expect(screen.getByText('用于解释该设置的完整说明')).toBeTruthy() + expect(screen.queryByRole('slider')).toBeNull() + expect(screen.queryByRole('menuitem', { name: /^模型/ })).toBeNull() + fireEvent.click(toggleButton) + expect(toggle).toHaveBeenCalledOnce() + expect(select).not.toHaveBeenCalled() + expect(screen.getByRole('menu')).toBeTruthy() + fireEvent.keyDown(toggleButton, { key: 'Escape' }) + expect(screen.queryByRole('switch')).toBeNull() + expect(screen.queryByText('用于解释该设置的完整说明')).toBeNull() + expect(screen.getByRole('slider', { name: '推理等级' })).toBeTruthy() + expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: '设置 关' })) + }) + + it('moves Tab from the inline range to a contributed entry and Shift+Tab back without changing effort', () => { + const { select } = mountPage() + const slider = screen.getByRole('slider', { name: '推理等级' }) + const model = screen.getByRole('menuitem', { name: /^模型/ }) + const entry = screen.getByRole('menuitem', { name: '设置 关' }) + slider.focus() + expect(fireEvent.keyDown(slider, { key: 'Tab' })).toBe(false) + expect(document.activeElement).toBe(entry) + slider.focus() + expect(fireEvent.keyDown(slider, { key: 'Tab', shiftKey: true })).toBe(false) + expect(document.activeElement).toBe(model) + expect(select).not.toHaveBeenCalled() + }) + + it('focuses the keyed page when it has no switch and Tabs through its controls', () => { + mountPage(false, false) + fireEvent.click(screen.getByRole('menuitem', { name: '设置 关' })) + const page = screen.getByRole('menu', { name: '示例设置' }) + expect(document.activeElement).toBe(page) + expect(fireEvent.keyDown(page, { key: 'Tab' })).toBe(false) + const report = screen.getByRole('button', { name: '报告失败' }) + expect(document.activeElement).toBe(report) + expect(fireEvent.keyDown(report, { key: 'Tab' })).toBe(false) + expect(document.activeElement).toBe(screen.getByRole('button', { name: '关闭设置' })) + expect(screen.getByRole('menu')).toBeTruthy() + }) + + it('passes pending selection locking into the keyed page while keeping Escape navigation available', () => { + const { directory, toggle } = mountPage() + fireEvent.click(screen.getByRole('menuitem', { name: '设置 关' })) + act(() => { directory.set(state({ status: 'selecting', pending: { provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' } })) }) + const switchButton = screen.getByRole('switch', { name: '启用示例设置' }) + expect(switchButton.hasAttribute('disabled')).toBe(true) + fireEvent.click(switchButton) + expect(toggle).not.toHaveBeenCalled() + fireEvent.keyDown(switchButton, { key: 'Escape' }) + expect(screen.getByRole('slider').hasAttribute('disabled')).toBe(false) + expect(screen.getByRole('slider').getAttribute('aria-disabled')).toBe('true') + }) + + it('retains detail controls after reported failure and lets the contribution dismiss with trigger focus', () => { + const { trigger } = mountPage() + fireEvent.click(screen.getByRole('menuitem', { name: '设置 关' })) + fireEvent.click(screen.getByRole('button', { name: '报告失败' })) + expect(screen.getByRole('alert').textContent).toBe('示例设置保存失败') + expect(screen.getByRole('switch', { name: '启用示例设置' })).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: '关闭设置' })) + expect(screen.queryByRole('menu')).toBeNull() + expect(document.activeElement).toBe(trigger) + expect(screen.getByRole('alert').textContent).toBe('示例设置保存失败') + }) +}) + it('dismisses contributed options with focus on the trigger before opening another overlay', () => { const renderSlot = vi.fn((_name: string, _owner: object) => null) render(-`) and the panel it controls (`--panel`), which the owner renders and points back at the tab with `aria-labelledby`; a segment may be `disabled` with a `title`, and `disabled` on the control locks every segment while the shown panel has work in flight. | | `Checkbox` | Labeled native checkbox with controlled state, keyboard interaction, and disabled styling; the caller supplies localized `label` text. `modalAutofocus` marks the input for its owning Modal's initial focus without moving focus itself. | | `Input` | Single-line text entry for search boxes and inline forms. Its ref targets the native input for focus and is cleared on unmount. | diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index f90076add7..ec24f5b701 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -43,7 +43,7 @@ kind: "package-library" | 导出 | 是什么 | |---|---| | `Button` | 可点击操作;`variant` 选择 `primary`、`ghost`、`outline` 或 `toolbar`。描边操作使用内侧细线。ref 指向原生按钮,供焦点控制与浮层锚定使用。 | -| `Switch` | 36×20 的双态开关。关闭态滑块读取 `--dsw-alias-switch-thumb`,在两种主题下均保持亮色;开启态滑块与品牌色轨道形成对比。禁用控件使用半透明样式。`label` 必填,控件不可能在没有名称的情况下发布。 | +| `Switch` | 36×20 的双态开关。关闭态滑块读取 `--dsw-alias-switch-thumb`,在两种主题下均保持亮色;开启态滑块与品牌色轨道形成对比。禁用控件使用半透明样式。可选的 `pending` 拒绝新变更并设置 `aria-disabled` 与 `aria-busy`,但不设置原生 `disabled`,因此保存期间保留焦点,除非 `disabled` 同时为 true。`label` 必填,控件不可能在没有名称的情况下发布。 | | `SegmentedControl` | 两段或更多等宽分段加一个滑动指示块的 tablist,用于在几种模式间切换一张卡片或面板;选中项由调用方持有,`label` 为列表命名。`id` 派生每个 tab 的 id(`-`)及其控制的面板 id(`--panel`),面板由调用方渲染并用 `aria-labelledby` 指回 tab;分段可 `disabled` 并带 `title`,控件级 `disabled` 在当前面板有进行中的操作时锁住全部分段。 | | `Checkbox` | 带标签的原生复选框,支持受控状态、键盘交互和禁用样式;调用方提供本地化的 `label` 文本。`modalAutofocus` 将输入标记为所属 Modal 的初始焦点,本身不会移动焦点。 | | `Input` | 单行文本输入,用于搜索框与行内表单。ref 指向原生输入框,供焦点控制使用,并在卸载时清空。 | diff --git a/packages/client/ui-primitives/src/Switch.tsx b/packages/client/ui-primitives/src/Switch.tsx index 980a08f6be..3a48484f76 100644 --- a/packages/client/ui-primitives/src/Switch.tsx +++ b/packages/client/ui-primitives/src/Switch.tsx @@ -9,17 +9,18 @@ import css from './Switch.module.css' * @param props.checked - the current state; the control is fully controlled. * @param props.onChange - called with the state the click asks for. * @param props.label - localized accessible name, owned by the render site. - * @param props.disabled - whether the control refuses input; owners also set it - * while a write is in flight, not only when a deployment locks the toggle. + * @param props.disabled - whether the control is unavailable and excluded from keyboard focus. + * @param props.pending - a write is in flight; refuse further changes while preserving focus. * @param props.title - localized hover text, typically why the toggle is locked. * @param props.className - extra class for layout placement. * @returns the switch element. */ -export function Switch({ checked, onChange, label, disabled = false, title, className }: { +export function Switch({ checked, onChange, label, disabled = false, pending = false, title, className }: { checked: boolean onChange: (next: boolean) => void label: string disabled?: boolean + pending?: boolean title?: string | undefined // `| undefined` so a caller can forward an optional class straight through // under exactOptionalPropertyTypes (a CSS-module lookup is string|undefined). @@ -33,8 +34,10 @@ export function Switch({ checked, onChange, label, disabled = false, title, clas aria-label={label} title={title} disabled={disabled} + aria-disabled={disabled || pending || undefined} + aria-busy={pending || undefined} className={clsx(css.switch, className)} - onClick={() => { onChange(!checked) }} + onClick={() => { if (!pending) onChange(!checked) }} > diff --git a/packages/client/ui-primitives/tests/switch.client.spec.tsx b/packages/client/ui-primitives/tests/switch.client.spec.tsx index a80eae48d3..6aef86cc3e 100644 --- a/packages/client/ui-primitives/tests/switch.client.spec.tsx +++ b/packages/client/ui-primitives/tests/switch.client.spec.tsx @@ -33,6 +33,39 @@ describe('Switch', () => { expect(onChange).not.toHaveBeenCalled() }) + it.each([false, true])('keeps focus while pending and refuses repeated activation (checked: %s)', (checked) => { + const onChange = vi.fn() + const { rerender } = render() + const control = screen.getByRole('switch') as HTMLButtonElement + control.focus() + rerender() + expect(control.disabled).toBe(false) + expect(control.getAttribute('aria-disabled')).toBe('true') + expect(control.getAttribute('aria-busy')).toBe('true') + expect(control.getAttribute('aria-checked')).toBe(String(checked)) + expect(document.activeElement).toBe(control) + fireEvent.click(control) + fireEvent.click(control) + expect(onChange).not.toHaveBeenCalled() + rerender() + expect(control.getAttribute('aria-disabled')).toBeNull() + expect(control.getAttribute('aria-busy')).toBeNull() + expect(document.activeElement).toBe(control) + fireEvent.click(control) + expect(onChange).toHaveBeenCalledExactlyOnceWith(!checked) + }) + + it('keeps a locked switch natively disabled while pending', () => { + const onChange = vi.fn() + render() + const control = screen.getByRole('switch') as HTMLButtonElement + expect(control.disabled).toBe(true) + expect(control.getAttribute('aria-disabled')).toBe('true') + expect(control.getAttribute('aria-busy')).toBe('true') + fireEvent.click(control) + expect(onChange).not.toHaveBeenCalled() + }) + it('carries a lock reason as the hover title when the owner names one', () => { render( {}} />) expect(screen.getByRole('switch').getAttribute('title')).toBe('Managed by policy') diff --git a/packages/client/ui-theme/src/styles/design-platform.css b/packages/client/ui-theme/src/styles/design-platform.css index 6c53a267a7..e17e4fbfbc 100644 --- a/packages/client/ui-theme/src/styles/design-platform.css +++ b/packages/client/ui-theme/src/styles/design-platform.css @@ -274,6 +274,8 @@ body { --dsw-alias-state-warn-primary: var(--dsw-static-amber-500); --dsw-alias-state-warn-secondary: var(--dsw-static-amber-400); --dsw-alias-state-warn-tertiary: var(--dsw-static-amber-100); + --dsw-alias-slider-thumb: var(--dsw-static-neutral-bluish-00); + --dsw-alias-slider-thumb-mark: var(--dsw-static-deepseek-500); --dsw-alias-switch-thumb: var(--dsw-static-neutral-bluish-00); --dsw-alias-toast-bg: var(--dsw-static-neutral-bluish-800); --dsw-alias-toast-label: var(--dsw-static-neutral-bluish-00); @@ -398,6 +400,8 @@ body[data-ds-dark-theme] { --dsw-alias-state-warn-primary: var(--dsw-static-amber-500); --dsw-alias-state-warn-secondary: var(--dsw-static-amber-400); --dsw-alias-state-warn-tertiary: var(--dsw-static-amber-900); + --dsw-alias-slider-thumb: var(--dsw-static-neutral-bluish-00); + --dsw-alias-slider-thumb-mark: var(--dsw-static-deepseek-500); --dsw-alias-switch-thumb: var(--dsw-static-neutral-bluish-400); --dsw-alias-toast-bg: var(--dsw-static-neutral-bluish-750); --dsw-alias-toast-label: var(--dsw-static-neutral-bluish-00); diff --git a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts index 04eeacf67a..83879bec56 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -1545,7 +1545,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.label\', () => ctx.slots.register(\n { name: \'conversation.input.model.label\' },\n ({ provider, model }) => React.createElement(\'span\', { title: provider.name }, model.name),\n ))\n },\n}', - source: 'packages/client/ui-model-selection/src/client/slots.ts:50', + source: 'packages/client/ui-model-selection/src/client/slots.ts:70', }, { key: 'conversation.input.model.options', @@ -1573,7 +1573,10 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ doc: 'Display text where the owner projects one (nav rows, tabs). A thunk is re-read on every projection, so localized text follows the active locale without re-registering.', }, ], - ownerProps: [], + ownerProps: [ + '/** Selection state and feedback shared by menu option entries and detail pages. */\nexport interface ModelMenuControls {\n /** Whether the composer currently refuses selection changes. */\n locked: boolean\n /** Close the menu and focus its trigger synchronously before opening another overlay. */\n dismiss: () => void\n /** Report a failed selection through the menu owner\'s persistent toast. */\n reportFailure: (message: string) => void\n}', + '/** A keyed contribution displayed as a second page of the model menu. */\nexport interface ModelMenuPage {\n /** Registration key in conversation.input.model.page; also marks its root button\'s data-model-menu-page. */\n key: string\n /** Localized accessible name of the detail page. */\n title: string\n}', + ], ownerPropsReferences: [], standardProps: [ 'useRemoteAccess: (action: RemoteEndpoint) => boolean', @@ -1605,7 +1608,57 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.options\', () => ctx.slots.register(\n { name: \'conversation.input.model.options\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-model-selection/src/client/slots.ts:23', + source: 'packages/client/ui-model-selection/src/client/slots.ts:41', + }, + { + key: 'conversation.input.model.page', + kind: 'keyed', + scope: 'session', + summary: 'Plugin-owned content displayed as a model-menu detail page.', + doc: 'Plugin-owned content displayed as a model-menu detail page.', + registerOptions: [ + { + name: 'key', + requirement: 'required', + type: 'string', + doc: 'Your cell key: the entry renders where the owner dispatches this exact key. Registering an already-occupied key replaces that occupant.', + }, + ], + ownerProps: [ + '/** Selection state and feedback shared by menu option entries and detail pages. */\nexport interface ModelMenuControls {\n /** Whether the composer currently refuses selection changes. */\n locked: boolean\n /** Close the menu and focus its trigger synchronously before opening another overlay. */\n dismiss: () => void\n /** Report a failed selection through the menu owner\'s persistent toast. */\n reportFailure: (message: string) => void\n}', + ], + ownerPropsReferences: [], + standardProps: [ + 'useRemoteAccess: (action: RemoteEndpoint) => boolean', + 'useResource: UseResource', + 'useContextMenu: UseContextMenu', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessions: UseSessions', + 'useSessionStatus: UseSessionStatus', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', + 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', + 'useChat: UseChat', + 'useConversation: UseConversation', + 'useInput: SnapshotSelectorHook', + 'inputActions: InputActions', + 'useSession: SessionSnapshotSelector', + 'sessionId: SessionId', + 'useProjection: UseProjection', + 'useAccess: (action: RemoteEndpoint) => boolean', + 'useTrajectory: UseTrajectory', + ], + keyDomain: 'open: any string the owner dispatches (no compile-time key set), already taken: agent-team', + hookContext: '', + slotInject: '', + declaredBy: 'an entry in \'conversation.input.model\' (client-ui-model-selection), so it exists while that entry is mounted', + occupants: [ + 'client-ui-agent-team TeamModePage key \'agent-team\'', + ], + replaceRisk: 'shadows-shipped-ui', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.page\', () => ctx.slots.register(\n { name: \'conversation.input.model.page\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/client/ui-model-selection/src/client/slots.ts:50', }, { key: 'conversation.input.overlay', From 603c26a9d796e90dd05f19d367842dd95208d3b6 Mon Sep 17 00:00:00 2001 From: Yif <877193178@qq.com> Date: Thu, 5 Nov 2026 15:47:19 +0800 Subject: [PATCH 003/450] feat(ui): refine model picker motion and localized effort controls Add localized effort labels and default explanations, animate the blue thumb center, and preserve focus and opacity while selections save. --- apps/web/tests/declared-reasoning.e2e.ts | 525 +++++++++++++++++- .../tests/deepseek-messages-settings.e2e.ts | 4 +- .../declared-reasoning/ui.expected.md | 3 +- apps/web/tests/model-menu-observer.e2e.ts | 6 +- .../client/ui-agent-team/README.i18n.yaml | 4 +- packages/client/ui-agent-team/README.md | 4 +- packages/client/ui-agent-team/README.zh.md | 4 +- .../src/client/TeamModeToggle.module.css | 6 +- .../src/client/TeamModeToggle.tsx | 12 +- .../tests/team-mode.client.spec.tsx | 79 ++- .../ui-model-selection/README.i18n.yaml | 12 +- packages/client/ui-model-selection/README.md | 12 +- .../client/ui-model-selection/README.zh.md | 12 +- .../src/client/EffortSlider.module.css | 218 ++++++-- .../src/client/EffortSlider.tsx | 192 +++++-- .../src/client/ModelSelect.tsx | 35 +- .../src/client/effort-label.ts | 24 + .../ui-model-selection/src/client/locales.ts | 88 ++- .../ui-model-selection/src/client/slots.ts | 4 +- .../tests/effort-label.client.spec.ts | 30 + .../tests/effort-slider.client.spec.tsx | 258 ++++++++- .../tests/model-menu-tab.client.spec.tsx | 90 ++- .../tests/model-select.client.spec.tsx | 109 +++- .../src/client/slot-catalog.ts | 10 +- 24 files changed, 1546 insertions(+), 195 deletions(-) create mode 100644 packages/client/ui-model-selection/src/client/effort-label.ts create mode 100644 packages/client/ui-model-selection/tests/effort-label.client.spec.ts diff --git a/apps/web/tests/declared-reasoning.e2e.ts b/apps/web/tests/declared-reasoning.e2e.ts index 95b6244e3b..c697d3dd84 100644 --- a/apps/web/tests/declared-reasoning.e2e.ts +++ b/apps/web/tests/declared-reasoning.e2e.ts @@ -6,7 +6,7 @@ import { readFile } from 'node:fs/promises' import { fileURLToPath } from 'node:url' import { join } from 'node:path' -import type { Browser, Locator, Page, Request } from 'playwright' +import type { Browser, Locator, Page, Request, Route } from 'playwright' import { chromium, webkit } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed, onTestFinished } from 'vitest' import { @@ -22,6 +22,57 @@ const UI_EXPECTED = fileURLToPath(new URL('./expected/declared-reasoning/ui.expe const POINTER_EXPECTED = fileURLToPath(new URL('./expected/declared-reasoning/pointer-menu.expected.md', import.meta.url)) const MODE = webSnapshotMode() +async function readEffortMotion(slider: Locator) { + return slider.evaluate((element) => { + const input = element as HTMLInputElement + const group = input.closest('[role="group"]')! + const thumb = group.querySelector('[data-effort-thumb]')! + const scale = group.querySelector('[data-effort-thumb-scale]')! + const fill = group.querySelector('[data-effort-fill]')! + const label = group.querySelector('[data-effort-label]')! + const rangeRect = input.getBoundingClientRect() + const thumbRect = thumb.getBoundingClientRect() + const fillRect = fill.getBoundingClientRect() + const labelRect = label.parentElement!.getBoundingClientRect() + const thumbSize = Number.parseFloat(getComputedStyle(thumb).width) + const ratio = (input.valueAsNumber - Number(input.min)) / (Number(input.max) - Number(input.min)) + return { + value: input.valueAsNumber, dragging: input.parentElement!.hasAttribute('data-dragging'), + nativeWidth: rangeRect.width, nativeHeight: rangeRect.height, + left: rangeRect.left, right: rangeRect.right, y: rangeRect.top + rangeRect.height / 2, + center: thumbRect.left + thumbRect.width / 2, centerY: thumbRect.top + thumbRect.height / 2, + expectedCenter: rangeRect.left + thumbSize / 2 + (rangeRect.width - thumbSize) * ratio, + thumbSize, visualWidth: scale.getBoundingClientRect().width, fillRight: fillRect.right, + dotWidth: Number.parseFloat(getComputedStyle(scale, '::after').width), + dotDuration: getComputedStyle(scale, '::after').transitionDuration, + dotEasing: getComputedStyle(scale, '::after').transitionTimingFunction, + labelCenter: labelRect.left + labelRect.width / 2, + thumbDuration: getComputedStyle(thumb).transitionDuration, + thumbEasing: getComputedStyle(thumb).transitionTimingFunction, + fillDuration: getComputedStyle(fill).transitionDuration, + tickDuration: getComputedStyle(group.querySelector('[data-effort-tick]')!).transitionDuration, + ticks: [...group.querySelectorAll('[data-effort-tick]')].map((tick) => { + const rect = tick.getBoundingClientRect() + return { center: rect.left + rect.width / 2, width: rect.width, + hovered: tick.hasAttribute('data-hovered'), visibility: getComputedStyle(tick).visibility } + }), + } + }) +} + +async function assertSettledEffort(slider: Locator) { + await expect.poll(async () => { + const view = await readEffortMotion(slider) + return Math.max(Math.abs(view.center - view.expectedCenter), Math.abs(view.fillRight - view.center)) + }).toBeLessThan(1) + const view = await readEffortMotion(slider) + expect(view.nativeHeight).toBe(40) + expect(view.thumbSize).toBe(20) + expect(Math.abs(view.centerY - view.y)).toBeLessThan(1) + expect(Math.abs(view.labelCenter - (view.left + view.right) / 2)).toBeLessThan(1) + return view +} + describe.skipIf(MODE === 'record').each([ { name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webkit }, @@ -85,16 +136,19 @@ describe.skipIf(MODE === 'record').each([ const rootModel = page.locator('[data-model-menu-root] > button[role="menuitem"]') const slider = page.getByRole('slider', { name: '推理等级', exact: true }) const team = page.locator('[data-model-menu-page="agent-team"]') + const info = page.getByRole('button', { name: '默认推理等级说明', exact: true }) const focused = async (locator: Locator): Promise => { await expect.poll(() => locator.evaluate(element => element === document.activeElement)).toBe(true) } await trigger.click() await page.keyboard.press('Tab'); await focused(rootModel) expect(await page.getByRole('menuitemradio').count()).toBe(0) + await page.keyboard.press('Tab'); await focused(info) await page.keyboard.press('Tab'); await focused(slider) await page.keyboard.press('Tab'); await focused(team) expect(await page.getByRole('switch').count()).toBe(0) await page.keyboard.press('Shift+Tab'); await focused(slider) + await page.keyboard.press('Shift+Tab'); await focused(info) await page.keyboard.press('Shift+Tab'); await focused(rootModel) await page.keyboard.press('Enter') const search = page.getByRole('searchbox', { name: '搜索模型…', exact: true }) @@ -116,6 +170,7 @@ describe.skipIf(MODE === 'record').each([ await page.keyboard.press('Tab') await focused(page.locator('[role="menuitemradio"][aria-checked="true"]')) await page.keyboard.press('Space'); await focused(rootModel) + await page.keyboard.press('Tab'); await focused(info) await page.keyboard.press('Tab'); await focused(slider) await page.keyboard.press('Tab'); await focused(team) await page.keyboard.press('Space') @@ -137,6 +192,76 @@ describe.skipIf(MODE === 'record').each([ expect(tripwire.pageErrors).toEqual([]) }, 60_000) + it('reads default information by mouse and keyboard without selecting or closing the menu', async () => { + const trigger = page.getByRole('button', { name: /^选择模型/ }) + let requests = 0 + const count = (request: Request): void => { + if (new URL(request.url()).pathname.endsWith('/session/selectModel')) requests++ + } + page.on('request', count) + try { + await trigger.click() + const menu = page.getByRole('menu', { name: '模型与推理等级', exact: true }) + const slider = menu.getByRole('slider', { name: '推理等级', exact: true }) + const info = menu.getByRole('button', { name: '默认推理等级说明', exact: true }) + const explanation = '未显式指定推理等级,将使用模型与配置的默认设置;这不代表关闭推理' + const defaultHeight = await menu.evaluate(element => element.getBoundingClientRect().height) + await menu.locator('[data-effort-label]').click() + expect(await slider.inputValue()).toBe('0') + await info.click() + const tooltip = page.getByRole('tooltip') + await tooltip.waitFor() + expect(await tooltip.textContent()).toBe(explanation) + expect(await menu.isVisible()).toBe(true) + await info.click() + await tooltip.waitFor({ state: 'hidden' }) + await trigger.focus() + await page.keyboard.press('Tab') + await page.keyboard.press('Tab') + expect(await info.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Enter') + await tooltip.waitFor() + await page.keyboard.press('Escape') + await tooltip.waitFor({ state: 'hidden' }) + expect(await menu.isVisible()).toBe(true) + expect(await info.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Space') + await tooltip.waitFor() + await page.keyboard.press('Tab') + await tooltip.waitFor({ state: 'hidden' }) + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + expect(requests).toBe(0) + await slider.press('ArrowRight') + await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBe('off') + expect(await slider.getAttribute('aria-valuetext')).toBe('关闭') + expect(await menu.locator('[data-effort-label]').textContent()).toBe('推理等级:关闭') + expect(await info.count()).toBe(0) + expect(await menu.evaluate(element => element.getBoundingClientRect().height)).toBe(defaultHeight) + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + await slider.press('Home') + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection()).toEqual({ + provider: 'acme-gateway', model: 'acme-think', + }) + expect(await info.count()).toBe(1) + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Shift+Tab') + await page.keyboard.press('Enter') + await tooltip.waitFor() + await page.keyboard.press('Escape') + await tooltip.waitFor({ state: 'hidden' }) + expect(await menu.isVisible()).toBe(true) + await page.keyboard.press('Escape') + await menu.waitFor({ state: 'hidden' }) + expect(await trigger.evaluate(element => element === document.activeElement)).toBe(true) + expect(requests).toBe(2) + expect(tripwire.pageErrors).toEqual([]) + } finally { + page.off('request', count) + if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() + } + }) + it('offers exactly the declared levels in the root slider and records one keyboard selection', async () => { onTestFailed(() => saveFailureShot(page, `web-e2e-declared-reasoning-${engine.name()}`)) const trigger = page.getByRole('button', { name: /^选择模型/ }) @@ -147,11 +272,12 @@ describe.skipIf(MODE === 'record').each([ await trigger.click() const slider = page.getByRole('slider', { name: '推理等级', exact: true }) const levels = page.getByRole('group', { name: '推理等级', exact: true }).getByRole('button') - expect(await levels.count()).toBe(0) + expect(await levels.count()).toBe(1) + expect(await levels.getAttribute('aria-label')).toBe('默认推理等级说明') expect(await slider.getAttribute('min')).toBe('0') expect(await slider.getAttribute('max')).toBe('3') - expect(await slider.getAttribute('aria-valuetext')).toBe('Default') - const tag = page.getByRole('group', { name: '推理等级', exact: true }).getByText('Default', { exact: true }) + expect(await slider.getAttribute('aria-valuetext')).toBe('默认') + const tag = page.getByRole('group', { name: '推理等级', exact: true }).getByText('推理等级:默认', { exact: true }) expect(await tag.evaluate(element => ({ cursor: getComputedStyle(element).cursor, userSelect: getComputedStyle(element).getPropertyValue(CSS.supports('user-select', 'none') ? 'user-select' : '-webkit-user-select'), @@ -177,8 +303,8 @@ describe.skipIf(MODE === 'record').each([ async () => readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8'), { timeout: 10_000 }, ).toContain('reasoningEffort: high') - await expect.poll(() => trigger.getAttribute('aria-label')).toBe('选择模型,当前 Acme Think,推理等级 High') - expect(await slider.getAttribute('aria-valuetext')).toBe('High') + await expect.poll(() => trigger.getAttribute('aria-label')).toBe('选择模型,当前 Acme Think,推理等级 高') + expect(await slider.getAttribute('aria-valuetext')).toBe('高') await slider.focus() await page.keyboard.press('Shift+Tab') await expect.poll(() => page.getByRole('menuitem', { name: /^模型/ }) @@ -272,16 +398,21 @@ describe.skipIf(MODE === 'record').each([ await expect.poll(() => rootModel.evaluate(element => getComputedStyle(element).backgroundColor)).not.toBe('rgba(0, 0, 0, 0)') await page.mouse.move(0, 0) await page.keyboard.press('Tab') + const info = page.getByRole('button', { name: '默认推理等级说明', exact: true }) + expect(await info.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Tab') const slider = page.getByRole('slider', { name: '推理等级', exact: true }) expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) await page.keyboard.press('Shift+Tab') + expect(await info.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Shift+Tab') expect(await rootModel.evaluate(element => element === document.activeElement)).toBe(true) expect(await rootModel.evaluate(element => getComputedStyle(element).backgroundColor)).not.toBe('rgba(0, 0, 0, 0)') expect(selections).toBe(1) const rangeBounds = await slider.boundingBox() if (rangeBounds === null) throw new Error('Reasoning slider is not visible') await page.mouse.click(rangeBounds.x + rangeBounds.width - 8, rangeBounds.y + rangeBounds.height / 2) - await expect.poll(() => slider.getAttribute('aria-valuetext')).toBe('Max') + await expect.poll(() => slider.getAttribute('aria-valuetext')).toBe('最高') expect(selections).toBe(2) await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort, { timeout: 10_000 }) .toBe('max') @@ -353,8 +484,9 @@ describe.skipIf(MODE === 'record').each([ const menu = page.getByRole('menu', { name: '模型与推理等级', exact: true }) const group = menu.getByRole('group', { name: '推理等级', exact: true }) const slider = group.getByRole('slider', { name: '推理等级', exact: true }) - expect(await group.getByRole('button').count()).toBe(0) - expect(await slider.getAttribute('aria-valuetext')).toBe('Default') + expect(await group.getByRole('button').count()).toBe(1) + expect(await group.getByRole('button').getAttribute('aria-label')).toBe('默认推理等级说明') + expect(await slider.getAttribute('aria-valuetext')).toBe('默认') expect(await slider.getAttribute('max')).toBe('5') await expect.poll(() => menu.evaluate((element) => { const rect = element.getBoundingClientRect() @@ -382,7 +514,7 @@ describe.skipIf(MODE === 'record').each([ label: input.getAttribute('aria-valuetext'), busy: input.getAttribute('aria-busy'), disabled: (input as HTMLInputElement).disabled, - }))).toEqual({ value: '5', label: 'Max', busy: 'false', disabled: false }) + }))).toEqual({ value: '5', label: '最高', busy: 'false', disabled: false }) } catch (error) { await page.screenshot({ path: fileURLToPath(new URL( `../../../.artifacts/model-picker-master-sync/drag-${engine.name()}-regression.png`, import.meta.url, @@ -403,6 +535,379 @@ describe.skipIf(MODE === 'record').each([ } }) + it('keeps visual motion aligned with native dragging, hover targets and pending saves at 390px', async () => { + onTestFailed(() => saveFailureShot(page, `web-e2e-effort-motion-${engine.name()}`)) + const viewport = page.viewportSize()! + const trigger = page.getByRole('button', { name: /^选择模型/ }) + try { + await trigger.click() + await page.getByRole('menuitem', { name: /^模型/ }).click() + await page.getByRole('menuitemradio', { name: 'Acme Lite', exact: true }).click() + await page.setViewportSize({ width: 390, height: 700 }) + const slider = page.getByRole('slider', { name: '推理等级', exact: true }) + await slider.press('Home') + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + await slider.hover() + await page.mouse.move(0, 0) + await expect.poll(async () => (await readEffortMotion(slider)).dotWidth).toBeCloseTo(8, 1) + const rest = await assertSettledEffort(slider) + await expect.poll(async () => (await readEffortMotion(slider)).visualWidth).toBeCloseTo(20, 1) + expect(rest.dotWidth).toBeCloseTo(8, 1) + expect(rest.thumbDuration).toBe('0.3s') + expect(rest.fillDuration).toBe('0.3s') + expect(rest.thumbEasing).toBe('cubic-bezier(0.23, 1, 0.32, 1)') + expect(rest.dotDuration.split(',').map(value => value.trim())).toEqual(['0.14s', '0.14s']) + expect(rest.dotEasing).toBe('cubic-bezier(0.23, 1, 0.32, 1), cubic-bezier(0.23, 1, 0.32, 1)') + expect(rest.tickDuration).toBe('0.12s') + await page.mouse.move(rest.center, rest.y) + await expect.poll(async () => (await readEffortMotion(slider)).dotWidth).toBeCloseTo(9.6, 1) + const expanded = await readEffortMotion(slider) + expect(expanded.visualWidth).toBeCloseTo(20, 1) + expect(Math.abs(expanded.center - rest.center)).toBeLessThan(1) + const tick = rest.ticks[2]! + await page.mouse.move(tick.center + 7, rest.y) + await expect.poll(async () => (await readEffortMotion(slider)).ticks[2]!.width).toBeCloseTo(8, 1) + const hovered = await readEffortMotion(slider) + expect(hovered.ticks.filter(point => point.hovered)).toHaveLength(1) + expect(Math.abs(hovered.ticks[2]!.center - tick.center)).toBeLessThan(1) + await page.mouse.move(tick.center + 9, rest.y) + await expect.poll(async () => (await readEffortMotion(slider)).ticks[2]!.width).toBeCloseTo(4, 1) + const release = Promise.withResolvers() + let requests = 0 + let forwarding: Promise | undefined + const holdSelection = (route: Route): Promise => { + requests++ + forwarding = (async () => { await release.promise; await route.continue() })() + return forwarding + } + await page.route('**/api/session/selectModel', holdSelection) + try { + const grabOffset = 6 + await page.mouse.move(rest.center + grabOffset, rest.y) + await page.mouse.down() + await expect.poll(async () => (await readEffortMotion(slider)).dotWidth).toBeCloseTo(9.6, 1) + expect((await readEffortMotion(slider)).visualWidth).toBeCloseTo(20, 1) + const step = (rest.nativeWidth - rest.thumbSize) / 5 + const between = rest.center + step * 0.3 + await page.mouse.move(between + grabOffset, rest.y, { steps: 3 }) + const tracking = await readEffortMotion(slider) + expect(tracking.value).toBe(0) + expect(Math.abs(tracking.center - between)).toBeLessThan(1) + expect(Math.abs(tracking.fillRight - tracking.center)).toBeLessThan(1) + expect(tracking.ticks.every(point => point.visibility === 'visible')).toBe(true) + expect(tracking.thumbDuration).toBe('0s') + expect(tracking.fillDuration).toBe('0s') + expect(Math.abs(tracking.labelCenter - rest.labelCenter)).toBeLessThan(1) + await page.mouse.move(tick.center + grabOffset, rest.y, { steps: 4 }) + const dragging = await readEffortMotion(slider) + expect(dragging.ticks.every(point => !point.hovered)).toBe(true) + expect(dragging.ticks.every(point => Math.abs(point.width - 4) < 0.1)).toBe(true) + await page.mouse.move(rest.right + 24, rest.y, { steps: 8 }) + expect(requests).toBe(0) + await page.mouse.up() + await expect.poll(() => requests).toBe(1) + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('true') + const pending = await assertSettledEffort(slider) + expect(pending.value).toBe(5) + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + expect(await slider.evaluate(element => (element as HTMLInputElement).disabled)).toBe(false) + await slider.press('ArrowLeft') + expect((await readEffortMotion(slider)).value).toBe(5) + expect(requests).toBe(1) + release.resolve(undefined) + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + const saved = await assertSettledEffort(slider) + expect(Math.abs(saved.center - pending.center)).toBeLessThan(1) + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + expect(requests).toBe(1) + } finally { + release.resolve(undefined) + await page.mouse.up() + await forwarding + await page.unroute('**/api/session/selectModel', holdSelection) + } + await page.mouse.move(rest.ticks[2]!.center, rest.y) + await page.mouse.down() + try { + await expect.poll(() => slider.inputValue()).toBe('2') + const clicked = await readEffortMotion(slider) + expect(clicked.dragging).toBe(false) + expect(clicked.thumbDuration).toBe('0.3s') + expect(clicked.fillDuration).toBe('0.3s') + } finally { + await page.mouse.up() + } + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + expect((await assertSettledEffort(slider)).value).toBe(2) + await slider.press('Home') + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + expect((await assertSettledEffort(slider)).value).toBe(0) + await page.emulateMedia({ reducedMotion: 'reduce' }) + await slider.press('End') + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + const reduced = await assertSettledEffort(slider) + expect(reduced.value).toBe(5) + expect(reduced.thumbDuration).toBe('0s') + expect(reduced.fillDuration).toBe('0s') + expect(reduced.dotDuration).toBe('0s') + expect(reduced.tickDuration).toBe('0s') + await page.mouse.move(reduced.center, reduced.y) + expect((await readEffortMotion(slider)).visualWidth).toBeCloseTo(20, 1) + expect((await readEffortMotion(slider)).dotWidth).toBeCloseTo(8, 1) + await page.mouse.move(reduced.ticks[2]!.center, reduced.y) + expect((await readEffortMotion(slider)).ticks[2]!.width).toBeCloseTo(4, 1) + expect(tripwire.pageErrors).toEqual([]) + } finally { + await page.mouse.up() + await page.emulateMedia({ reducedMotion: null }) + if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() + await page.setViewportSize(viewport) + } + }) + + it('does not leave thumb or tick hover enlarged after a native touch tap', async () => { + const touch = await browser.newPage({ + viewport: { width: 390, height: 700 }, locale: ZH_BROWSER_LOCALE, hasTouch: true, isMobile: true, + }) + const consoleWatch = watchConsole(touch) + try { + await touch.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await connectFreshWorkspaceZh(touch, scaffold.workspaceCwd) + await touch.getByRole('button', { name: /^选择模型/ }).click() + await touch.getByRole('menuitem', { name: /^模型/ }).click() + await touch.getByRole('menuitemradio', { name: 'Acme Lite', exact: true }).click() + const slider = touch.getByRole('slider', { name: '推理等级', exact: true }) + await slider.press('Home') + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + const before = await assertSettledEffort(slider) + expect(before.value).toBe(0) + expect(await touch.evaluate(() => matchMedia('(hover: hover) and (pointer: fine)').matches)).toBe(false) + let requests = 0 + const count = (request: Request): void => { + if (new URL(request.url()).pathname.endsWith('/session/selectModel')) requests++ + } + touch.on('request', count) + try { + const info = touch.getByRole('button', { name: '默认推理等级说明', exact: true }) + const bounds = await info.boundingBox() + if (bounds === null) throw new Error('Default information is not visible') + await touch.touchscreen.tap(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2) + const tooltip = touch.getByRole('tooltip') + await tooltip.waitFor() + expect(await tooltip.textContent()).toBe('未显式指定推理等级,将使用模型与配置的默认设置;这不代表关闭推理') + expect(await slider.inputValue()).toBe('0') + expect(requests).toBe(0) + await touch.touchscreen.tap(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2) + await tooltip.waitFor({ state: 'hidden' }) + expect(await info.isVisible()).toBe(true) + await touch.touchscreen.tap(before.right - 10, before.y) + await expect.poll(() => slider.inputValue()).toBe('5') + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + await assertSettledEffort(slider) + await expect.poll(async () => (await readEffortMotion(slider)).visualWidth).toBeCloseTo(20, 1) + await expect.poll(async () => (await readEffortMotion(slider)).dotWidth).toBeCloseTo(8, 1) + expect(await touch.locator('[data-effort-thumb-scale][data-expanded]').count()).toBe(0) + expect((await readEffortMotion(slider)).ticks.every(tick => !tick.hovered && Math.abs(tick.width - 4) < 0.1)).toBe(true) + expect(requests).toBe(1) + expect(consoleWatch.pageErrors).toEqual([]) + } finally { + touch.off('request', count) + } + } finally { + await touch.close() + } + }) + + it('keeps the compact Spanish caption and default information readable at 390px', async () => { + const probe = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: 'es-ES' }) + const consoleWatch = watchConsole(probe) + try { + await probe.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await probe.getByRole('button', { name: 'Agregar espacio de trabajo', exact: true }).click() + const directory = probe.getByRole('dialog', { name: 'Seleccionar carpeta de trabajo', exact: true }) + await directory.getByRole('button', { name: 'Editar ruta', exact: true }).click() + const path = directory.getByRole('textbox', { name: 'Editar ruta', exact: true }) + await path.fill(join(scaffold.workspaceCwd, 'workspace')) + await path.press('Enter') + await directory.getByRole('button', { name: 'Abrir', exact: true }).click() + await probe.locator('[data-composer-input][contenteditable="true"]').waitFor() + await probe.getByRole('button', { name: /^Seleccionar modelo/ }).click() + await probe.getByRole('menuitem', { name: /^modelo/ }).click() + await probe.getByRole('menuitemradio', { name: 'Acme Lite', exact: true }).click() + const menu = probe.getByRole('menu', { name: 'Esfuerzo de modelo y razonamiento.', exact: true }) + const slider = menu.getByRole('slider', { name: 'Esfuerzo', exact: true }) + await slider.press('Home') + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + await probe.setViewportSize({ width: 390, height: 700 }) + const label = menu.locator('[data-effort-label]') + const info = menu.getByRole('button', { name: 'Acerca del esfuerzo de razonamiento predeterminado', exact: true }) + await info.waitFor() + const layout = await info.evaluate((button) => { + const tag = button.parentElement! + const text = tag.querySelector('[data-effort-label]')! + const name = text.querySelector('[data-effort-name]')! + const prefix = name.previousElementSibling! + const bounds = button.getBoundingClientRect() + const tagBounds = tag.getBoundingClientRect() + const nameBounds = name.getBoundingClientRect() + const hit = document.elementFromPoint(bounds.left + bounds.width / 2, bounds.top + bounds.height / 2) + return { width: bounds.width, height: bounds.height, textWidth: text.clientWidth, + textGap: bounds.left - text.getBoundingClientRect().right, endInset: tagBounds.right - bounds.right, + clipped: prefix.scrollWidth > prefix.clientWidth, ellipsis: getComputedStyle(prefix).textOverflow, + nameText: name.textContent, nameFits: name.scrollWidth <= name.clientWidth, + nameVisible: nameBounds.width > 0 && nameBounds.left >= tagBounds.left && nameBounds.right <= bounds.left, + contained: bounds.left >= tagBounds.left && bounds.right <= tagBounds.right, + reachable: hit?.closest('button') === button } + }) + expect(layout).toMatchObject({ width: 24, height: 24, clipped: false, ellipsis: 'ellipsis', + nameText: 'Predeterminado', nameFits: true, nameVisible: true, contained: true, reachable: true }) + expect(layout.textWidth).toBeGreaterThan(0) + expect(layout.textGap).toBeCloseTo(2, 1) + expect(layout.endInset).toBeCloseTo(2, 1) + expect(await label.textContent()).toBe('Esfuerzo: Predeterminado') + await label.hover() + const tooltip = probe.getByRole('tooltip') + expect(await tooltip.count()).toBe(0) + await info.click() + await expect.poll(() => tooltip.allTextContents()).toEqual([ + 'No se ha seleccionado explícitamente un esfuerzo de razonamiento. Se aplican los valores predeterminados del modelo y de la configuración; esto no significa que el razonamiento esté desactivado.', + ]) + expect(await menu.isVisible()).toBe(true) + expect(await slider.inputValue()).toBe('0') + await probe.keyboard.press('Escape') + await tooltip.waitFor({ state: 'hidden' }) + expect(await menu.isVisible()).toBe(true) + await info.focus() + await probe.keyboard.press('Enter') + await tooltip.waitFor() + await probe.keyboard.press('Tab') + await tooltip.waitFor({ state: 'hidden' }) + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + expect(await slider.inputValue()).toBe('0') + expect(consoleWatch.pageErrors).toEqual([]) + } finally { + await probe.close() + } + }) + + it.each(['success', 'failure'] as const)('keeps Team undimmed and guarded through a pending effort %s', async (outcome) => { + const trigger = page.getByRole('button', { name: /^选择模型/ }) + const release = Promise.withResolvers() + let selections = 0 + let teamWrites = 0 + let forwarding: Promise | undefined + const countTeamWrites = (request: Request): void => { + if (new URL(request.url()).pathname.endsWith('/agentTeams/setEnabled')) teamWrites++ + } + const holdSelection = (route: Route): Promise => { + selections++ + forwarding = (async () => { + await release.promise + if (outcome === 'success') { await route.continue(); return } + const envelope = route.request().postDataJSON() as { rpcId: string } + await route.fulfill({ json: { type: 'server-response', rpcId: envelope.rpcId, result: { + ok: false, error: { code: 'session/writer-held', message: 'held', details: { sessionId: 'team-pending-fixture' } }, + } } }) + })() + return forwarding + } + await trigger.click() + await page.getByRole('menuitem', { name: /^模型/ }).click() + await page.getByRole('menuitemradio', { name: 'Acme Lite', exact: true }).click() + const slider = page.getByRole('slider', { name: '推理等级', exact: true }) + await slider.press('Home') + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + await page.keyboard.down('ArrowRight') + await page.keyboard.down('ArrowRight') + await page.keyboard.down('ArrowRight') + await page.keyboard.up('ArrowRight') + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBe('high') + await page.mouse.move(0, 0) + const menuLocator = page.getByRole('menu', { name: '模型与推理等级', exact: true }) + const teamLocator = page.locator('[data-model-menu-page="agent-team"]') + const menu = await menuLocator.elementHandle() + const root = await page.locator('[data-model-menu-root]').elementHandle() + const team = await teamLocator.elementHandle() + if (menu === null || root === null || team === null) throw new Error('Missing pending Team controls') + const sample = () => page.evaluate(({ menu, root, team }) => { + const rect = (element: Element) => { + const value = element.getBoundingClientRect() + return { x: value.x, y: value.y, width: value.width, height: value.height } + } + return { + same: { + menu: menu === document.querySelector('[role="menu"][aria-label="模型与推理等级"]'), + root: root === document.querySelector('[data-model-menu-root]'), + team: team === document.querySelector('[data-model-menu-page="agent-team"]'), + }, + connected: menu.isConnected && root.isConnected && team.isConnected, + rect: { menu: rect(menu), root: rect(root), team: rect(team) }, + disabled: (team as HTMLButtonElement).disabled, opacity: getComputedStyle(team).opacity, + ariaDisabled: team.getAttribute('aria-disabled'), ariaBusy: team.getAttribute('aria-busy'), + focus: document.activeElement === team ? 'team' : document.activeElement === root.querySelector('input[type="range"]') ? 'range' : 'other', + } + }, { menu, root, team }) + page.on('request', countTeamWrites) + try { + const before = await sample() + expect(before).toMatchObject({ same: { menu: true, root: true, team: true }, connected: true, + disabled: false, opacity: '1', ariaDisabled: null, ariaBusy: null, focus: 'range' }) + await page.route('**/api/session/selectModel', holdSelection) + await page.keyboard.down('ArrowLeft') + await page.keyboard.down('ArrowLeft') + await page.keyboard.up('ArrowLeft') + await expect.poll(() => selections).toBe(1) + await expect.poll(() => teamLocator.getAttribute('aria-busy')).toBe('true') + const during = await sample() + expect(during).toEqual({ ...before, ariaDisabled: 'true', ariaBusy: 'true' }) + const bounds = during.rect.team + await page.mouse.click(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2) + expect(await menuLocator.getByRole('switch').count()).toBe(0) + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Tab') + expect(await teamLocator.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Enter') + await page.keyboard.press('Space') + expect(await teamLocator.evaluate(element => element === document.activeElement)).toBe(true) + expect(await menuLocator.getByRole('switch').count()).toBe(0) + expect(teamWrites).toBe(0) + expect(selections).toBe(1) + release.resolve(undefined) + await expect.poll(() => teamLocator.getAttribute('aria-busy')).toBeNull() + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + const after = await sample() + expect(after).toEqual({ ...before, focus: 'team' }) + expect(await teamLocator.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Shift+Tab') + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + expect(scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBe(outcome === 'success' ? 'low' : 'high') + if (outcome === 'failure') await page.getByRole('alert').waitFor() + expect(selections).toBe(1) + expect(teamWrites).toBe(0) + const lockedOpacity = await team.evaluate((element) => { + const button = element as HTMLButtonElement + try { button.disabled = true; return getComputedStyle(button).opacity } finally { button.disabled = false } + }) + expect(lockedOpacity).toBe('0.5') + await page.keyboard.press('Tab') + expect(await teamLocator.evaluate(element => element === document.activeElement)).toBe(true) + await teamLocator.click() + await page.getByRole('switch', { name: '启用智能体团队协作', exact: true }).waitFor() + expect(teamWrites).toBe(0) + expect(tripwire.pageErrors).toEqual([]) + } finally { + release.resolve(undefined) + await forwarding + await page.unroute('**/api/session/selectModel', holdSelection) + page.off('request', countTeamWrites) + await menu.dispose() + await root.dispose() + await team.dispose() + if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() + } + }) + it('keeps its snapshot inventory closed', async () => { await assertFixtureInventory(SNAPSHOT_DIR, ['ui.expected.md', 'pointer-menu.expected.md']) }) diff --git a/apps/web/tests/deepseek-messages-settings.e2e.ts b/apps/web/tests/deepseek-messages-settings.e2e.ts index a842669c01..5a5c6727cc 100644 --- a/apps/web/tests/deepseek-messages-settings.e2e.ts +++ b/apps/web/tests/deepseek-messages-settings.e2e.ts @@ -128,8 +128,8 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett const slider = effort.getByRole('slider') expect(await slider.getAttribute('min')).toBe('0') expect(await slider.getAttribute('max')).toBe('3') - expect(await slider.getAttribute('aria-valuetext')).toBe('High') - const tag = effort.getByText('High', { exact: true }) + expect(await slider.getAttribute('aria-valuetext')).toBe('高') + const tag = effort.getByText('推理等级:高', { exact: true }) expect(await tag.evaluate(element => getComputedStyle(element).fontWeight)).toBe('500') expect(await tag.evaluate(element => element.tabIndex)).toBe(-1) expect(tripwire.pageErrors).toEqual([]) diff --git a/apps/web/tests/expected/declared-reasoning/ui.expected.md b/apps/web/tests/expected/declared-reasoning/ui.expected.md index a56dedf7d1..4ad2a55d90 100644 --- a/apps/web/tests/expected/declared-reasoning/ui.expected.md +++ b/apps/web/tests/expected/declared-reasoning/ui.expected.md @@ -1,6 +1,7 @@ - menu "模型与推理等级": - menuitem "模型 Acme Think" - group "推理等级": - - text: Default + - text: 推理等级:默认 + - button "默认推理等级说明" - slider "推理等级": "0" - menuitem "智能体团队协作 关" diff --git a/apps/web/tests/model-menu-observer.e2e.ts b/apps/web/tests/model-menu-observer.e2e.ts index d0a1cab304..5dfc2d06d3 100644 --- a/apps/web/tests/model-menu-observer.e2e.ts +++ b/apps/web/tests/model-menu-observer.e2e.ts @@ -413,7 +413,9 @@ describe.skipIf(webSnapshotMode() === 'record').each([ await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: 2.5 }) await expect.poll(() => page.evaluate(() => window.visualViewport!.scale)).toBe(2.5) expect(Number(await slider.getAttribute('max'))).toBeGreaterThanOrEqual(7) - expect(await menu.getByRole('group', { name: '推理等级', exact: true }).getByRole('button').count()).toBe(0) + const information = menu.getByRole('group', { name: '推理等级', exact: true }).getByRole('button') + expect(await information.count()).toBe(1) + expect(await information.getAttribute('aria-label')).toBe('默认推理等级说明') await expect.poll(() => slider.evaluate((range) => { const scroller = range.closest('[data-model-menu-root]')! scroller.scrollTop = scroller.scrollHeight @@ -457,7 +459,7 @@ describe.skipIf(webSnapshotMode() === 'record').each([ await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }) await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection()).toMatchObject({ reasoningEffort: 'max' }) expect(await menu.isVisible()).toBe(true) - await expect.poll(() => slider.getAttribute('aria-valuetext')).toBe('Max') + await expect.poll(() => slider.getAttribute('aria-valuetext')).toBe('最高') await page.keyboard.press('Escape') await menu.waitFor({ state: 'detached' }) } diff --git a/packages/client/ui-agent-team/README.i18n.yaml b/packages/client/ui-agent-team/README.i18n.yaml index a438e29119..e7ab86a3a4 100644 --- a/packages/client/ui-agent-team/README.i18n.yaml +++ b/packages/client/ui-agent-team/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-agent-team/use-this-package: - en: 1bb905cfddfc8686 - zh: f3996e9b43e2b06b + en: 5485135ed71fbbf5 + zh: 37112168c8785012 /deepseek-ai-dsh-client-ui-agent-team/use-this-package/inspect-the-task-board: en: 2f606827b3ab14bc zh: 7f713d10268e7498 diff --git a/packages/client/ui-agent-team/README.md b/packages/client/ui-agent-team/README.md index bd556a4873..f94c571c56 100644 --- a/packages/client/ui-agent-team/README.md +++ b/packages/client/ui-agent-team/README.md @@ -25,7 +25,9 @@ This package displays shared tasks below the Subagent tree in one header panel. ## Use this package -In the root conversation’s model and reasoning menu, select **Agent teamwork** to open its settings page, then turn on **Enable agent teamwork**. The root row shows only the saved On/Off state and opens the page without changing the selection; the settings page places the switch above the full explanation. New Sessions default to off. While enabled, open the root conversation’s Subagent control to see members above shared tasks. Child conversations keep subagent navigation without a task board or Team switch, including before their subagent address is discovered. The entry is hidden when both the subagent catalog and shared tasks are empty; catalog and task-record errors remain accessible. Section headers appear only when Team mode is enabled, at least one nondeleted shared task exists, and the task footer is available. In that case, the noncollapsible Subagents section remains above shared tasks even when its catalog is empty. Otherwise, the menu shows only subagent navigation, without section headers, a shared-task module, empty-state copy, or a divider. Turning it off retains tasks and subagents. The settings page shows the shared-task coordination, complex-task results, and token-cost explanation as ordinary text, without an information tooltip. Its entire switch row highlights on hover and toggles the selection when clicked. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving. Saving uses the [Switch pending state](../ui-primitives/README.md#component-catalog), so a keyboard-activated switch keeps focus without accepting another change. +In the root conversation’s model and reasoning menu, select **Agent teamwork** to open its settings page, then turn on **Enable agent teamwork**. The root row shows only the saved On/Off state and opens the page without changing the selection; the settings page places the switch above the full explanation. New Sessions default to off. While enabled, open the root conversation’s Subagent control to see members above shared tasks. Child conversations keep subagent navigation without a task board or Team switch, including before their subagent address is discovered. The entry is hidden when both the subagent catalog and shared tasks are empty; catalog and task-record errors remain accessible. Section headers appear only when Team mode is enabled, at least one nondeleted shared task exists, and the task footer is available. In that case, the noncollapsible Subagents section remains above shared tasks even when its catalog is empty. Otherwise, the menu shows only subagent navigation, without section headers, a shared-task module, empty-state copy, or a divider. Turning it off retains tasks and subagents. The settings page shows the shared-task coordination, complex-task results, and token-cost explanation as ordinary text, without an information tooltip. Its entire switch row highlights on hover and toggles the selection when clicked. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving. The settings switch combines model-menu pending state with its own save state through the [Switch pending state](../ui-primitives/README.md#component-catalog). Either pending save blocks another Team change while keeping keyboard focus; it does not bypass the disable confirmation. + +During a model or reasoning-effort save, the root Team row keeps its opacity and focus and refuses activation. It reports `aria-disabled` and `aria-busy` without setting native `disabled`. An actual composer lock still sets native `disabled` and retains the disabled appearance. Turning off the menu switch requires confirmation after the Session records a model request; a model choice alone does not require it. The switch waits while request history is unavailable. The dialog explains the tool, coordination, and possible cache effects without deleting task records. Cancel, Escape, or closing the dialog leaves Team mode unchanged. Dismissing the dialog returns focus to the model selector. Confirmation targets the originating Session, waits for the save, and keeps failures visible for retry; it does not depend on the model menu remaining open. Team mode has no slash command; menu changes create no `command/run` or `command/done` records. diff --git a/packages/client/ui-agent-team/README.zh.md b/packages/client/ui-agent-team/README.zh.md index 115fb82e4c..e906b386f7 100644 --- a/packages/client/ui-agent-team/README.zh.md +++ b/packages/client/ui-agent-team/README.zh.md @@ -25,7 +25,9 @@ kind: "package-reference" ## 使用本包 -在根会话的模型与推理等级菜单中选择**智能体团队协作**,进入二级设置页后打开**启用智能体团队协作**。一级行只显示已保存的开/关状态,点击仅进入页面,不改变选择;二级页面将开关放在完整说明文字上方。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。设置页以普通正文显示共享任务协调、复杂任务效果与 token 开销的说明,不使用信息 tooltip。开关所在整行在悬停时高亮,点击可切换状态。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。保存时使用 [Switch 的 pending 状态](../ui-primitives/README.zh.md#component-catalog),因此键盘激活的开关保留焦点,但不接受再次切换。 +在根会话的模型与推理等级菜单中选择**智能体团队协作**,进入二级设置页后打开**启用智能体团队协作**。一级行只显示已保存的开/关状态,点击仅进入页面,不改变选择;二级页面将开关放在完整说明文字上方。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。设置页以普通正文显示共享任务协调、复杂任务效果与 token 开销的说明,不使用信息 tooltip。开关所在整行在悬停时高亮,点击可切换状态。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。设置页将模型菜单的 pending 状态与自身保存状态合并为 [Switch 的 pending 状态](../ui-primitives/README.zh.md#component-catalog)。任一保存进行中都会阻止再次切换 Team,同时保留键盘焦点;这不会绕过关闭确认。 + +模型或推理等级保存期间,一级 Team 行保持原有不透明度和焦点,并拒绝激活。它设置 `aria-disabled` 与 `aria-busy`,但不设置原生 `disabled`。输入区真正锁定时,仍设置原生 `disabled` 并保留禁用外观。 会话记录过模型请求后,从菜单开关停用团队需要确认;仅选择模型不会触发确认。请求历史尚未加载时,开关暂不可操作。弹窗说明工具、协作与可能的缓存影响,不会删除任务记录。取消、按 Escape 或关闭弹窗都保持团队状态不变。弹窗关闭后,焦点回到模型选择按钮。确认操作绑定到最初的会话,等待保存完成,失败时保留错误供重试,不依赖模型菜单保持打开。Team 模式没有斜杠命令;菜单切换不会生成 `command/run` 或 `command/done` 记录。 diff --git a/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css b/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css index 44916c8f26..5071a9c00b 100644 --- a/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css +++ b/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css @@ -45,7 +45,7 @@ .page { display: flex; flex-direction: column; - gap: 8px; + gap: 4px; min-width: 0; } @@ -53,8 +53,8 @@ margin: 0; padding: 4px 8px; color: var(--dsw-alias-label-secondary); - font-size: 13px; - line-height: 20px; + font-size: 12px; + line-height: 18px; overflow-wrap: anywhere; } diff --git a/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx b/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx index 15f6c93cae..a1b4b52dd6 100644 --- a/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx +++ b/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx @@ -36,7 +36,7 @@ export function TeamModeToggle(props: TeamModeToggleProps) { return } -function RootTeamModeSummary({ useProjection, locked, openPage, t }: TeamModeToggleProps) { +function RootTeamModeSummary({ useProjection, locked, pending, openPage, t }: TeamModeToggleProps) { const mode = useProjection('agentTeam') if (mode === undefined) return null return ( @@ -46,7 +46,9 @@ function RootTeamModeSummary({ useProjection, locked, openPage, t }: TeamModeTog className={css.summary} data-model-menu-page="agent-team" disabled={locked} - onClick={() => { openPage({ key: 'agent-team', title: t('command.title') }) }} + aria-disabled={locked || pending || undefined} + aria-busy={pending || undefined} + onClick={() => { if (!locked && !pending) openPage({ key: 'agent-team', title: t('command.title') }) }} > {t('command.title')} {t(mode.enabled ? 'mode.on' : 'mode.off')} @@ -69,14 +71,14 @@ export function TeamModePage(props: TeamModePageProps) { /** Read and change the selection only for root Sessions. */ function RootTeamModePage({ - useProjection, locked, dismiss, reportFailure, selectTeamMode, requestDisableConfirmation, t, + useProjection, locked, pending: modelPending, dismiss, reportFailure, selectTeamMode, requestDisableConfirmation, t, }: TeamModePageProps) { const mode = useProjection('agentTeam') const modelSelection = useProjection('modelSelection') const [pending, setPending] = useState(false) if (mode === undefined) return null const select = (enabled: boolean): void => { - if (locked || pending || modelSelection === undefined) return + if (locked || modelPending || pending || modelSelection === undefined) return if (!enabled && modelSelection.lastUsed !== null) { dismiss() requestDisableConfirmation() @@ -94,7 +96,7 @@ function RootTeamModePage({
{t('mode.label')} + pending={modelPending || pending} label={t('mode.label')} onChange={select} />

{t('mode.description')}

diff --git a/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx b/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx index 9fa08dacc9..82029d9af2 100644 --- a/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx +++ b/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx @@ -19,7 +19,8 @@ function props(enabled: boolean | undefined, selectTeamMode = vi.fn(async () => useProjection: (key: string) => key === 'modelSelection' ? requestedModel === 'loading' ? undefined : { lastUsed: requestedModel ? { provider: 'mock', model: 'mock' } : null, next: { provider: 'mock', model: 'mock' } } : enabled === undefined ? undefined : { enabled, tasks: [] }, - locked: false, openPage: vi.fn(), dismiss: vi.fn(), reportFailure: vi.fn(), selectTeamMode, requestDisableConfirmation: vi.fn(), + locked: false, pending: false, openPage: vi.fn(), dismiss: vi.fn(), reportFailure: vi.fn(), + selectTeamMode, requestDisableConfirmation: vi.fn(), t: makeTranslate(zh), } as TestProps } @@ -55,6 +56,82 @@ it('keeps summary state projection-owned and blocks navigation while locked', () expect(lockedInput.openPage).not.toHaveBeenCalled() }) +it.each([false, true])('keeps the summary node focused and natively enabled during a model save (enabled: %s)', (enabled) => { + const input = props(enabled) + const view = render() + const summary = screen.getByRole('menuitem') + summary.focus() + view.rerender() + expect(screen.getByRole('menuitem')).toBe(summary) + expect(summary.isConnected).toBe(true) + expect(summary.hasAttribute('disabled')).toBe(false) + expect(summary.getAttribute('aria-disabled')).toBe('true') + expect(summary.getAttribute('aria-busy')).toBe('true') + expect(document.activeElement).toBe(summary) + fireEvent.click(summary) + expect(input.openPage).not.toHaveBeenCalled() + expect(input.selectTeamMode).not.toHaveBeenCalled() + view.rerender() + expect(screen.getByRole('menuitem')).toBe(summary) + expect(summary.getAttribute('aria-disabled')).toBeNull() + expect(summary.getAttribute('aria-busy')).toBeNull() + expect(document.activeElement).toBe(summary) + fireEvent.click(summary) + expect(input.openPage).toHaveBeenCalledOnce() +}) + +it.each([false, true])('blocks Team writes and confirmation without dropping switch focus during a model save (enabled: %s)', (enabled) => { + const input = props(enabled, undefined, undefined, true) + const view = render() + const toggle = screen.getByRole('switch') + toggle.focus() + view.rerender() + expect(screen.getByRole('switch')).toBe(toggle) + expect(toggle.hasAttribute('disabled')).toBe(false) + expect(toggle.getAttribute('aria-disabled')).toBe('true') + expect(toggle.getAttribute('aria-busy')).toBe('true') + fireEvent.click(toggle) + expect(input.selectTeamMode).not.toHaveBeenCalled() + expect(input.requestDisableConfirmation).not.toHaveBeenCalled() + expect(input.dismiss).not.toHaveBeenCalled() + expect(document.activeElement).toBe(toggle) + view.rerender() + expect(toggle.getAttribute('aria-disabled')).toBeNull() + expect(toggle.getAttribute('aria-busy')).toBeNull() + expect(document.activeElement).toBe(toggle) +}) + +it.each([TeamModeToggle, TeamModePage])('keeps a genuine lock natively disabled while a model write is pending', (Component) => { + const input = props(false) + render() + const control = screen.queryByRole('menuitem') ?? screen.getByRole('switch') + expect(control.hasAttribute('disabled')).toBe(true) + expect(control.getAttribute('aria-disabled')).toBe('true') + expect(control.getAttribute('aria-busy')).toBe('true') + fireEvent.click(control) + expect(input.openPage).not.toHaveBeenCalled() + expect(input.selectTeamMode).not.toHaveBeenCalled() +}) + +it('keeps model pending protection after the Team write settles', async () => { + const pending = Promise.withResolvers() + onTestFinished(async () => { await act(async () => { pending.resolve(null) }) }) + const input = props(false, vi.fn(() => pending.promise)) + const view = render() + const toggle = screen.getByRole('switch') + toggle.focus() + fireEvent.click(toggle) + view.rerender() + await act(async () => { pending.resolve(null) }) + expect(toggle.getAttribute('aria-busy')).toBe('true') + expect(toggle.hasAttribute('disabled')).toBe(false) + fireEvent.click(toggle) + expect(input.selectTeamMode).toHaveBeenCalledTimes(1) + view.rerender() + expect(toggle.getAttribute('aria-busy')).toBeNull() + expect(document.activeElement).toBe(toggle) +}) + it('allows reading settings from the summary while model history loads', () => { const input = props(false, undefined, undefined, 'loading') render() diff --git a/packages/client/ui-model-selection/README.i18n.yaml b/packages/client/ui-model-selection/README.i18n.yaml index 3d37eb7f75..b0e74e370d 100644 --- a/packages/client/ui-model-selection/README.i18n.yaml +++ b/packages/client/ui-model-selection/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-model-selection/use-this-package: - en: 8caa289a6b9a3987 - zh: 4e68187154ad7a01 + en: 9b301384eb14f6e0 + zh: 7b021daf345506a8 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/model-and-effort: - en: 7444798cb92d0f38 - zh: 03edcc1070554437 + en: a57ad8d1ae2c5378 + zh: 391f4a695cdb5232 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/model-label-extensions: en: 8da3af8ae98adbb3 zh: b411b32d6b2b9e04 @@ -27,8 +27,8 @@ en: 7f20428c747ff052 zh: 975e6de728e02fa0 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/selection-failures: - en: 393aae0df60e2abd - zh: f989d6108a047160 + en: 7f5e8e8358c98376 + zh: 5df89a5a0934c885 /deepseek-ai-dsh-client-ui-model-selection/understand-the-implementation: en: feab134e75f5b2f7 zh: 66bd58568f58ed4f diff --git a/packages/client/ui-model-selection/README.md b/packages/client/ui-model-selection/README.md index 55adbc748d..1d28797205 100644 --- a/packages/client/ui-model-selection/README.md +++ b/packages/client/ui-model-selection/README.md @@ -33,7 +33,7 @@ When no model is selected or the saved selection is absent from the catalog, the 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. In the root menu, `↑`/`↓` move between the model row, reasoning slider, and contributed options. A focused slider keeps arrow, Home, and End keys for its own value; Tab and Shift+Tab move to the adjacent control. In model search, arrows move the highlight and Enter selects it. Tab and Shift+Tab traverse search, its clear button, and the highlighted model without selecting; focused buttons activate with Enter or Space. Detail pages have no visible title or Back button. Escape returns to the root and restores the invoking row's focus; pressing Escape again closes the menu and focuses its trigger. Returning from the model list with Escape or after a successful model selection restores focus to the root model row without its grey background. Subsequent pointer movement or Tab navigation restores normal hover and focus styling. Phones and tablets leave model search unfocused until the user taps it or uses keyboard navigation. Removing a model or provider, including sign-out, preserves the saved route and effort without displaying their IDs; restoring its catalog entry restores its name and caption. -Mouse selection uses native browser clicks, including their cancellation behavior; a press alone never selects. Opening the root menu focuses its trigger, and clicking the trigger again closes it. Selecting a model returns to the root menu and its model row; changing effort keeps the menu and slider focus in place. While a model selection is pending, the trigger and chosen model-list row show spinners. Pending selections retain their target value and block duplicate submissions without a loading cursor; an effort save also keeps slider focus. A rejected selection leaves the menu and previous selection available for retry. Settings detail pages retain native Tab traversal. +Mouse selection uses native browser clicks, including their cancellation behavior; a press alone never selects. Opening the root menu focuses its trigger, and clicking the trigger again closes it. Selecting a model returns to the root menu and its model row; changing effort does not move focus or change the current menu page. While a model selection is pending, the trigger and chosen model-list row show spinners. Pending selections retain their target value and block duplicate submissions without a loading cursor; effort-save completion preserves any page or focus the user navigated to while saving. A rejected selection leaves the menu and previous selection available for retry. Settings detail pages retain native Tab traversal. ### Model and effort @@ -45,7 +45,13 @@ Both entries group models by provider, with DeepSeek Account first and DeepSeek The composer replaces the model and effort text with the Models icon when the expanded controls cannot share one line, and restores the text when space permits. The full selection remains available in the trigger's accessible name, tooltip, and menu. -The 260px-wide root menu places the model name above a centered effort tag and a native slider with discrete stops for the exact model's ordered reasoning choices. The tag uses the default cursor and its text cannot be selected; hovering still shows the localized “Reasoning effort: {effort}” tooltip without adding a Tab stop. Pointer drags preview locally and submit once on release; keyboard adjustments submit on key release. Escape during adjustment cancels the preview, and changing models discards any unfinished gesture. A `Default` stop appears only when the adapter has no configured default effort and submits no explicit effort; it is not a promise of a fixed provider strength. A single supported stop is readable but not draggable. No arbitrary token budget is entered here. +The 260px-wide root menu places the model name above a centered, arrowless effort tag and a native slider with discrete stops for the exact model's ordered reasoning choices. The tag displays the complete localized label, such as “Effort: High”, and keeps its hover tooltip. It uses the default cursor, its text cannot be selected, and the label adds no Tab stop. Pointer drags preview locally and submit once on release; keyboard adjustments submit on key release. Escape during adjustment cancels the preview, and changing models discards any unfinished gesture. + +The tag shows “Effort: Default” for the localized “Default” stop, which appears only when the adapter has no configured default effort. It submits no explicit effort: model and configuration defaults apply, which does not mean reasoning is off. Only this omitted-effort choice shows a keyboard-focusable information button beside the tag; a provider level with the explicit ID `default` does not. A single supported stop is readable but not draggable. No arbitrary token budget is entered here. + +Standard levels (`off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`) use localized names only when the provider's name matches its ID ignoring case. Custom names and unknown levels remain unchanged; for example, `high` named “Thorough mode” keeps that name. This changes display text only, not submitted or persisted IDs. + +The visual thumb and filled track follow pointer movement continuously during a drag; the native range still determines the discrete label and value, with one submission on release. Hovering the thumb with a fine mouse pointer or pressing the slider enlarges only the blue center of the visual thumb; the white disc and hit area keep their size. Mouse hover enlarges only the nearby tick, not neighboring ticks, and is inactive during dragging or saving. Touch interaction leaves no hover highlight. Reduced motion disables position transitions and center and tick enlargement. ### Model label extensions @@ -63,7 +69,7 @@ Catalog availability does not block sending with a saved selection; request exec When another writer owns the Session, model-selection failures tell the user to quit other running DSH instances and retry. -The session-scoped `conversation.input.model.options` list slot appends root options below model and reasoning controls. Its owner props expose `locked`, `reportFailure(message)`, `dismiss()`, and `openPage({ key, title })`. A root option marks its button with `data-model-menu-page` equal to its registration key and opens that key in `conversation.input.model.page`, a session-scoped keyed slot. The menu owner supplies scrolling, Escape navigation, focus return, and an accessible page name from `title`, without a visible title or Back button; the page receives `locked`, `reportFailure`, and `dismiss`, while its owning plugin retains all settings and confirmation logic. `dismiss()` closes the entire menu and focuses its trigger before another overlay opens. +The session-scoped `conversation.input.model.options` list slot appends root options below model and reasoning controls. Its owner props expose `locked`, required `pending: boolean`, `reportFailure(message)`, `dismiss()`, and `openPage({ key, title })`. A root option marks its button with `data-model-menu-page` equal to its registration key and opens that key in `conversation.input.model.page`, a session-scoped keyed slot. The menu owner supplies scrolling, Escape navigation, focus return, and an accessible page name from `title`, without a visible title or Back button; the page receives `locked`, `pending`, `reportFailure`, and `dismiss`, while its owning plugin retains all settings and confirmation logic. Both slots distinguish an actual composer lock (`locked`) from a model or effort save in flight (`pending`); saving alone does not set `locked`. `dismiss()` closes the entire menu and focuses its trigger before another overlay opens. ----- diff --git a/packages/client/ui-model-selection/README.zh.md b/packages/client/ui-model-selection/README.zh.md index f92ff2ffdd..14de3a0337 100644 --- a/packages/client/ui-model-selection/README.zh.md +++ b/packages/client/ui-model-selection/README.zh.md @@ -33,7 +33,7 @@ DeepSeek 账号和 API Key 路由显示为独立提供方分组,各自展示 与 `ui-conversation` 及命令包一起挂载本插件;composer 随即在待处理指示器旁显示模型位,`/model` 则以弹窗打开同一份目录。根菜单内,`↑`/`↓` 在模型行、推理滑块和扩展选项间移动。滑块聚焦后,方向键、Home 和 End 用于调整自身档位;Tab 和 Shift+Tab 移至相邻控件。模型搜索框内,方向键移动高亮,Enter 选定。Tab 和 Shift+Tab 在搜索框、清除按钮与高亮模型之间移动,不提交选择;按钮聚焦后用 Enter 或 Space 激活。二级页不显示标题或返回按钮。Escape 返回一级并恢复入口行焦点,再按一次则关闭菜单并聚焦触发器。从模型列表按 Escape 返回或成功选定模型后,焦点回到一级模型行,但不显示灰色底色。随后再次移动鼠标或使用 Tab 导航时,恢复正常的悬停与焦点样式。手机和平板在用户主动点按搜索框或使用键盘导航前,不聚焦搜索框。模型或提供方被删除时(包括账号退登),保留已保存的路由与推理强度,但不展示其 ID;目录条目恢复后重新显示名称与强度。 -鼠标选择沿用浏览器原生点击及其取消行为;仅按下按钮不会选定。打开根菜单时聚焦触发按钮,再次点击该按钮会关闭菜单。选定模型后回到一级菜单并聚焦模型行;调整推理等级后保持菜单打开和滑块焦点。等待模型选择结果时,触发器和模型列表待选行显示加载图标。选择保存期间保留目标值,阻止重复提交,但不显示加载鼠标;推理等级保存期间也保留滑块焦点。选择失败后保留菜单及原选择,允许重试。设置二级页保留原生 Tab 焦点遍历。 +鼠标选择沿用浏览器原生点击及其取消行为;仅按下按钮不会选定。打开根菜单时聚焦触发按钮,再次点击该按钮会关闭菜单。选定模型后回到一级菜单并聚焦模型行;调整推理等级不搬移焦点,也不切换当前菜单页面。等待模型选择结果时,触发器和模型列表待选行显示加载图标。选择保存期间保留目标值,阻止重复提交,但不显示加载鼠标;推理等级保存完成后,保留用户在保存期间主动导航到的页面与焦点。选择失败后保留菜单及原选择,允许重试。设置二级页保留原生 Tab 焦点遍历。 ### 模型与推理强度 @@ -45,7 +45,13 @@ composer 菜单中的模型名称使用 400(regular)字重;当前推理等 展开的控件无法排在同一行时,composer 将模型与推理强度文字替换为模型图标;空间足够后恢复文字。触发器的无障碍名称、提示和菜单仍提供完整选择。 -260px 宽的一级菜单将模型名放在上方,下方显示居中的推理等级标签与原生滑块,滑块以离散刻度表示当前模型公布的有序推理选项。标签使用默认鼠标指针,文字不可选中;悬停仍显示本地化的“推理等级:{effort}”提示,不增加 Tab 焦点。拖动时只在本地预览,松手后提交一次;键盘调整在松键时提交。调整过程中按 Escape 取消预览,切换模型会丢弃尚未结束的手势。仅当适配器未配置默认强度时出现 `Default` 刻度,它不提交显式强度,也不承诺提供方会使用固定档位。只有一个支持档位时仍可阅读,但不能拖动。此处不输入任意 token 预算。 +260px 宽的一级菜单将模型名放在上方,下方显示居中且不带箭头的推理等级标签与原生滑块,滑块以离散刻度表示当前模型公布的有序推理选项。标签显示完整本地化文案,例如“推理等级:高”,并保留悬停提示。标签使用默认鼠标指针,文字不可选中,文字本身不增加 Tab 焦点。拖动时只在本地预览,松手后提交一次;键盘调整在松键时提交。调整过程中按 Escape 取消预览,切换模型会丢弃尚未结束的手势。 + +仅当适配器未配置默认强度时出现本地化的“默认”刻度,标签显示“推理等级:默认”。它不提交显式推理等级,而是使用模型与配置的默认设置,不代表关闭推理。仅此省略等级的选择在标签旁显示可通过键盘聚焦的信息按钮;提供方显式 ID 为 `default` 的档位不显示该说明按钮。只有一个支持档位时仍可阅读,但不能拖动。此处不输入任意 token 预算。 + +标准档位(`off`、`minimal`、`low`、`medium`、`high`、`xhigh` 和 `max`)仅在提供方名称与 ID 忽略大小写后相同时使用本地化名称。自定义名称与未知档位保持原文,例如名称为“Thorough mode”的 `high` 保留该名称。此规则仅改变显示文字,不改变提交或持久化的 ID。 + +拖动期间,可见滑块圆点与轨道填充连续跟随指针移动;标签和实际值仍由原生滑块的离散档位决定,松手后只提交一次。精细鼠标指针悬停圆点或按下滑块时,只放大可见圆点中间的蓝色部分;白色外圈和命中区域尺寸不变。鼠标悬停仅放大命中的单个刻度,不放大相邻刻度;拖动或保存期间不启用刻度悬停效果。触摸交互不留下悬停高亮。减少动态效果设置会关闭位置过渡以及蓝点和刻度的放大效果。 ### 模型名称扩展 @@ -63,7 +69,7 @@ composer 菜单中的模型名称使用 400(regular)字重;当前推理等 当会话被其他写句柄占用时,模型选择失败提示用户退出其他正在运行的 DSH 后重试。 -会话级列表 slot `conversation.input.model.options` 在模型与推理控件下方追加一级选项。Owner props 提供 `locked`、`reportFailure(message)`、`dismiss()` 和 `openPage({ key, title })`。一级选项在按钮上设置与注册 key 相同的 `data-model-menu-page`,并打开会话作用域 keyed slot `conversation.input.model.page` 中的对应 key。菜单 owner 负责滚动、Escape 导航、焦点返回,以及由 `title` 提供的页面无障碍名称,不显示标题或返回按钮;二级页接收 `locked`、`reportFailure` 与 `dismiss`,所属插件保留全部设置与确认业务逻辑。`dismiss()` 关闭整个菜单并聚焦触发按钮,随后可打开其他浮层。 +会话级列表 slot `conversation.input.model.options` 在模型与推理控件下方追加一级选项。Owner props 提供 `locked`、必填的 `pending: boolean`、`reportFailure(message)`、`dismiss()` 和 `openPage({ key, title })`。一级选项在按钮上设置与注册 key 相同的 `data-model-menu-page`,并打开会话作用域 keyed slot `conversation.input.model.page` 中的对应 key。菜单 owner 负责滚动、Escape 导航、焦点返回,以及由 `title` 提供的页面无障碍名称,不显示标题或返回按钮;二级页接收 `locked`、`pending`、`reportFailure` 与 `dismiss`,所属插件保留全部设置与确认业务逻辑。两个 slot 均区分输入区的真实锁定(`locked`)与模型或推理等级正在保存(`pending`);仅保存中不会将 `locked` 设为 true。`dismiss()` 关闭整个菜单并聚焦触发按钮,随后可打开其他浮层。 ----- diff --git a/packages/client/ui-model-selection/src/client/EffortSlider.module.css b/packages/client/ui-model-selection/src/client/EffortSlider.module.css index 645a5f5b61..38e05015f9 100644 --- a/packages/client/ui-model-selection/src/client/EffortSlider.module.css +++ b/packages/client/ui-model-selection/src/client/EffortSlider.module.css @@ -8,13 +8,18 @@ grid-row: 2; display: flex; justify-content: center; - height: 22px; + height: 28px; margin: 10px 14px 0; } .value { + display: inline-flex; + align-items: center; + gap: 4px; + box-sizing: border-box; max-width: 100%; - padding: 1px 10px; + height: 28px; + padding: 1px 8px; border: 1px solid color-mix(in srgb, var(--dsw-alias-state-business-primary) 45%, transparent); border-radius: 999px; corner-shape: round; @@ -25,21 +30,97 @@ font-weight: 500; text-align: center; white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; cursor: default; -webkit-user-select: none; user-select: none; } +.value:has(.infoButton) { + gap: 2px; + padding-inline-end: 1px; +} + +.valueLabel { + display: flex; + gap: 2px; + min-width: 0; + overflow: hidden; + -webkit-user-select: none; + user-select: none; +} + +.valuePrefix { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; +} + +.valueName { + flex: 0 0 auto; + max-width: calc(100% - 2px); + overflow: hidden; + text-overflow: ellipsis; +} + +.infoButton { + display: inline-flex; + flex: 0 0 24px; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + padding: 0; + border: 0; + border-radius: 50%; + corner-shape: round; + background: transparent; + color: inherit; + cursor: pointer; +} + +.infoButton:focus-visible { + outline: 2px solid currentColor; + outline-offset: -2px; +} + +@media (hover: hover) { + .infoButton:hover { + background: var(--dsw-alias-interactive-bg-hover); + } +} + .rail { grid-row: 3; position: relative; margin: 0 8px 2px; } +.track { + position: absolute; + inset-inline: 0; + top: 50%; + height: var(--effort-track-size); + transform: translateY(-50%); + border-radius: 999px; + corner-shape: round; + overflow: hidden; + pointer-events: none; + background: color-mix(in srgb, var(--dsw-alias-label-primary) 5%, transparent); +} + +.fill { + display: block; + height: 100%; + width: calc(var(--effort-thumb-size) / 2 + (100% - var(--effort-thumb-size)) * var(--effort-visual-position)); + background: linear-gradient(to right, + color-mix(in srgb, var(--dsw-alias-state-business-primary) 8%, transparent), + color-mix(in srgb, var(--dsw-alias-state-business-primary) 54%, transparent)); + transition: width 300ms cubic-bezier(.23, 1, .32, 1); +} + .range { appearance: none; + position: relative; display: block; box-sizing: border-box; width: 100%; @@ -54,56 +135,32 @@ .range::-webkit-slider-runnable-track { height: var(--effort-track-size); - border-radius: 999px; - corner-shape: round; - background: - linear-gradient(to right, - color-mix(in srgb, var(--dsw-alias-state-business-primary) 8%, transparent) 0, - color-mix(in srgb, var(--dsw-alias-state-business-primary) 54%, transparent) var(--effort-progress), - color-mix(in srgb, var(--dsw-alias-label-primary) 5%, transparent) var(--effort-progress), - color-mix(in srgb, var(--dsw-alias-label-primary) 5%, transparent) 100%), - color-mix(in srgb, var(--dsw-alias-label-primary) 5%, transparent); -} - -.range::-moz-range-track { - height: var(--effort-track-size); - border-radius: 999px; - corner-shape: round; - background: color-mix(in srgb, var(--dsw-alias-label-primary) 5%, transparent); + background: transparent; } +.range::-moz-range-track, .range::-moz-range-progress { height: var(--effort-track-size); - border-radius: 999px; - corner-shape: round; - background: linear-gradient(to right, - color-mix(in srgb, var(--dsw-alias-state-business-primary) 8%, transparent), - color-mix(in srgb, var(--dsw-alias-state-business-primary) 54%, transparent)); + background: transparent; } - - +/* Native thumb geometry owns hit testing; the inert sibling owns all visual motion. */ .range::-webkit-slider-thumb { appearance: none; + box-sizing: border-box; width: var(--effort-thumb-size); height: var(--effort-thumb-size); margin-top: calc((var(--effort-track-size) - var(--effort-thumb-size)) / 2); - border: 0.5px solid var(--dsw-alias-border-l2); - border-radius: 50%; - corner-shape: round; - background: radial-gradient(circle, var(--dsw-alias-slider-thumb-mark) 0 4px, var(--dsw-alias-slider-thumb) 4.5px); - box-shadow: var(--dsw-elevation-panel); + border: 0; + background: transparent; } .range::-moz-range-thumb { box-sizing: border-box; width: var(--effort-thumb-size); height: var(--effort-thumb-size); - border: 0.5px solid var(--dsw-alias-border-l2); - border-radius: 50%; - corner-shape: round; - background: radial-gradient(circle, var(--dsw-alias-slider-thumb-mark) 0 4px, var(--dsw-alias-slider-thumb) 4.5px); - box-shadow: var(--dsw-elevation-panel); + border: 0; + background: transparent; } .range:focus-visible { @@ -113,29 +170,102 @@ } .range:disabled { - opacity: 0.5; cursor: default; } -.ticks { +.rail[data-disabled] { + opacity: 0.5; +} + +.ticks, +.thumbRail { position: absolute; inset: 0 calc(var(--effort-thumb-size) / 2); - display: flex; - align-items: center; - justify-content: space-between; pointer-events: none; } .tick, .tickActive { + position: absolute; + top: 50%; width: 4px; height: 4px; + transform: translate(-50%, -50%); border-radius: 50%; corner-shape: round; background: var(--dsw-alias-label-caption); opacity: 0.6; + transition: transform 120ms ease; } -.ticks [data-current] { - visibility: hidden; +@media (hover: hover) and (pointer: fine) { + .ticks [data-hovered] { + transform: translate(-50%, -50%) scale(2); + } +} + +.thumbPosition { + position: absolute; + top: 50%; + left: calc(var(--effort-visual-position) * 100%); + width: var(--effort-thumb-size); + height: var(--effort-thumb-size); + transform: translate(-50%, -50%); + transition: left 300ms cubic-bezier(.23, 1, .32, 1); +} + +.thumb { + position: absolute; + inset: 0; + box-sizing: border-box; + border: 0.5px solid var(--dsw-alias-border-l2); + border-radius: 50%; + corner-shape: round; + background: var(--dsw-alias-slider-thumb); + box-shadow: var(--dsw-elevation-panel); +} + +/* The white disc holds its size; only the blue center grows on hover or press. */ +.thumb::after { + content: ''; + position: absolute; + top: 50%; + left: 50%; + width: 8px; + height: 8px; + border-radius: 50%; + corner-shape: round; + background: var(--dsw-alias-slider-thumb-mark); + transform: translate(-50%, -50%); + transition: width 140ms cubic-bezier(.23, 1, .32, 1), height 140ms cubic-bezier(.23, 1, .32, 1); +} + +.thumb[data-expanded]::after { + width: 9.6px; + height: 9.6px; +} + +.rail[data-dragging] .thumbPosition, +.rail[data-dragging] .fill { + transition: none; +} + +@media (prefers-reduced-motion: reduce) { + .thumbPosition, + .fill, + .thumb::after, + .thumb[data-expanded]::after, + .tick, + .tickActive { + transition: none; + } + + .thumb[data-expanded]::after { + width: 8px; + height: 8px; + } + + .ticks [data-hovered] { + transform: translate(-50%, -50%); + } } diff --git a/packages/client/ui-model-selection/src/client/EffortSlider.tsx b/packages/client/ui-model-selection/src/client/EffortSlider.tsx index 301055506f..1c42361954 100644 --- a/packages/client/ui-model-selection/src/client/EffortSlider.tsx +++ b/packages/client/ui-model-selection/src/client/EffortSlider.tsx @@ -1,5 +1,5 @@ -import { useState, type CSSProperties } from 'react' -import { Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' +import { useEffect, useRef, useState, type CSSProperties, type PointerEvent } from 'react' +import { IconInfoOutlineRegular, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' import css from './EffortSlider.module.css' /** One adapter-advertised stop; undefined selects the adapter's default behavior. */ @@ -15,38 +15,114 @@ export interface EffortSliderProps { value: string | undefined label: string currentLabel: string - /** Localized tooltip text for the currently displayed effort name. */ - formatTooltip: (effort: string) => string + /** Localized full label for the currently displayed effort name. */ + formatLabel: (effort: string) => string + /** Accessible label for the default-effort explanation button. */ + defaultInfoLabel: string + /** Explanation of unspecified effort, distinct from disabling reasoning. */ + defaultExplanation: string disabled: boolean /** A selection is being saved; keep its displayed value and keyboard focus. */ pending: boolean onSelect: (effort: string | undefined) => void } -type Gesture = { kind: 'pointer' | 'keyboard' | 'cancelled'; source: string; index: number } +type PointerGeometry = { start: number; length: number; size: number; centerY: number; offset: number } +type Gesture = + | { kind: 'pointer'; source: string; index: number; geometry: PointerGeometry | null; position: number | null } + | { kind: 'keyboard' | 'cancelled'; source: string; index: number } + | { kind: 'hover'; catalog: string; thumb: boolean; tick: number | null } const ADJUST_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', 'PageUp', 'PageDown']) /** - * Preview a discrete selection locally and submit once when the gesture finishes. + * Preview native discrete values while an inert visual thumb follows pointer movement. * @param props - Exact-model choices, persisted value, and selection callback. - * @returns A native discrete range with a live value label. + * @returns A native range with a live value label and independent motion decoration. */ -export function EffortSlider({ choices, value, label, currentLabel, formatTooltip, disabled, pending, onSelect }: EffortSliderProps) { +export function EffortSlider({ + choices, value, label, currentLabel, formatLabel, defaultInfoLabel, defaultExplanation, disabled, pending, onSelect, +}: EffortSliderProps) { + const thumbRef = useRef(null) + const rangeRef = useRef(null) + const infoFocused = useRef(false) const selectedIndex = choices.findIndex(choice => choice.effort === value) - const source = JSON.stringify([choices.map(choice => [choice.key, choice.effort]), value]) + const catalog = JSON.stringify(choices.map(choice => [choice.key, choice.effort])) + const source = JSON.stringify([catalog, value]) const [gesture, setGesture] = useState(null) - const preview = gesture?.source === source && gesture.kind !== 'cancelled' ? gesture.index : selectedIndex + const rangeDisabled = disabled || selectedIndex < 0 || choices.length < 2 + if (gesture?.kind === 'hover' && (gesture.catalog !== catalog || rangeDisabled)) setGesture(null) + if (gesture !== null && gesture.kind !== 'hover' && gesture.kind !== 'cancelled' + && (gesture.source !== source || rangeDisabled || pending)) { + setGesture({ kind: 'cancelled', source, index: selectedIndex }) + } + const active = gesture !== null && gesture.kind !== 'hover' && gesture.source === source && !rangeDisabled && !pending ? gesture : null + const hover = gesture?.kind === 'hover' && gesture.catalog === catalog && !rangeDisabled ? gesture : null + const preview = active !== null && active.kind !== 'cancelled' ? active.index : selectedIndex const index = Math.max(0, preview) const current = choices[preview] - const rangeDisabled = disabled || selectedIndex < 0 || choices.length < 2 - const commit = (nextIndex: number): void => { - const choice = choices[nextIndex] - setGesture(null) - if (!disabled && !pending && choice !== undefined) onSelect(choice.effort) + const defaultSelected = current !== undefined && current.effort === undefined + const displayName = current?.label ?? currentLabel + const valueLabel = formatLabel(displayName) + // Preserve the effort name when a long localized prefix needs truncation. + const valueStart = Math.max(0, valueLabel.lastIndexOf(displayName)) + useEffect(() => { + // An external selection can remove the focused info button; keep keyboard access on the range. + if (!defaultSelected && infoFocused.current) { + rangeRef.current?.focus() + infoFocused.current = false + } + }, [defaultSelected]) + const progress = choices.length > 1 ? index / (choices.length - 1) : 0 + const dragging = active?.kind === 'pointer' && active.position !== null + const visualProgress = dragging ? active.position : progress + const expanded = active?.kind === 'pointer' || hover?.thumb === true + + // Pointer geometry comes from the unscaled wrapper, so zoom and the spring cannot change the grab offset. + const measure = (input: HTMLInputElement): PointerGeometry | null => { + const range = input.getBoundingClientRect() + const thumb = thumbRef.current?.getBoundingClientRect() + if (thumb === undefined || range.width <= thumb.width) return null + return { + start: range.left + thumb.width / 2, length: range.width - thumb.width, + size: thumb.width, centerY: range.top + range.height / 2, offset: 0, + } } - const finish = (kind: Gesture['kind'], nextIndex: number): void => { - if (gesture?.kind === kind && gesture.source === source) commit(nextIndex) - else setGesture(null) + const hoverAt = (event: PointerEvent, settledIndex?: number): Gesture | null => { + if (rangeDisabled || event.pointerType !== 'mouse' || !window.matchMedia('(hover: hover) and (pointer: fine)').matches) return null + const geometry = measure(event.currentTarget) + const thumb = thumbRef.current?.getBoundingClientRect() + if (geometry === null || thumb === undefined) return null + const center = settledIndex === undefined ? thumb.left + thumb.width / 2 + : geometry.start + settledIndex / (choices.length - 1) * geometry.length + const overThumb = Math.abs(event.clientX - center) <= geometry.size / 2 + && Math.abs(event.clientY - geometry.centerY) <= geometry.size / 2 + const nearest = Math.max(0, Math.min(choices.length - 1, + Math.round((event.clientX - geometry.start) / geometry.length * (choices.length - 1)))) + const tickX = geometry.start + nearest / (choices.length - 1) * geometry.length + const overTick = !pending && !overThumb && Math.abs(event.clientX - tickX) <= 8 && Math.abs(event.clientY - geometry.centerY) <= 8 + return { kind: 'hover', catalog, thumb: overThumb, tick: overTick ? nearest : null } + } + const commit = (nextIndex: number, next: Gesture | null = null): void => { + const choice = choices[nextIndex] + setGesture(next) + if (!rangeDisabled && !pending && choice !== undefined) onSelect(choice.effort) + } + const finish = (kind: 'pointer' | 'keyboard', nextIndex: number, next: Gesture | null = null): void => { + if (gesture?.kind === kind && gesture.source === source) commit(nextIndex, next) + else setGesture(next) + } + const movePointer = (event: PointerEvent): void => { + if (gesture?.kind === 'cancelled') return + if (gesture?.kind === 'pointer') { + if (gesture.source !== source || rangeDisabled || pending || gesture.geometry === null) return + const { start, length, offset } = gesture.geometry + const position = Math.max(0, Math.min(1, (event.clientX - start - offset) / length)) + setGesture(previous => previous?.kind === 'pointer' && previous.source === source ? { ...previous, position } : previous) + } else if (gesture === null || gesture.kind === 'hover') { + const next = hoverAt(event) + setGesture(previous => previous?.kind === 'hover' && next?.kind === 'hover' + && previous.catalog === next.catalog && previous.thumb === next.thumb && previous.tick === next.tick ? previous : next) + } } return (
1 ? index / (choices.length - 1) * 100 : 0}%`, + '--effort-progress': `${progress * 100}%`, } as CSSProperties} >
- - {current?.label ?? currentLabel} + + + + {valueLabel.slice(0, valueStart)} + {valueLabel.slice(valueStart)} + + {defaultSelected && ( + + + + )} +
-
+
+ { - if (pending) { event.preventDefault(); return } - setGesture({ kind: 'pointer', source, index }) + if (pending || rangeDisabled) { event.preventDefault(); return } + if (event.button > 0) return + const geometry = measure(event.currentTarget) + const thumb = thumbRef.current?.getBoundingClientRect() + if (geometry !== null && thumb !== undefined) { + const offset = event.clientX - thumb.left - thumb.width / 2 + if (Math.abs(offset) <= geometry.size / 2 && Math.abs(event.clientY - geometry.centerY) <= geometry.size / 2) { + geometry.offset = offset + } + } + setGesture({ kind: 'pointer', source, index, geometry, position: null }) }} + onPointerEnter={movePointer} + onPointerMove={movePointer} + onPointerLeave={() => { setGesture(previous => previous?.kind === 'hover' ? null : previous) }} onChange={(event) => { - if (pending || disabled) return + if (pending || rangeDisabled) return const nextIndex = event.currentTarget.valueAsNumber - if (gesture === null) commit(nextIndex) - else if (gesture.source === source && gesture.kind !== 'cancelled') setGesture({ ...gesture, index: nextIndex }) + if (gesture === null || gesture.kind === 'hover') commit(nextIndex) + else if (gesture.source === source && gesture.kind !== 'cancelled') { + setGesture(previous => previous !== null && previous.kind !== 'hover' && previous.source === source && previous.kind !== 'cancelled' + ? { ...previous, index: nextIndex } : previous) + } + }} + onPointerUp={(event) => { + if (gesture?.kind === 'pointer' && gesture.source === source && !rangeDisabled && !pending) event.currentTarget.focus() + finish('pointer', event.currentTarget.valueAsNumber, hoverAt(event, event.currentTarget.valueAsNumber)) }} - onPointerUp={(event) => { finish('pointer', event.currentTarget.valueAsNumber) }} onPointerCancel={() => { setGesture(null) }} - onLostPointerCapture={() => { setGesture(null) }} - onBlur={() => { setGesture(null) }} + onLostPointerCapture={() => { setGesture(previous => previous?.kind === 'hover' ? previous : null) }} + onBlur={(event) => { + // WebKit focuses the enclosing menu when its native range takes over a pointer drag. + const insideAncestor = event.relatedTarget instanceof Node && event.relatedTarget.contains(event.currentTarget) + setGesture(previous => insideAncestor && previous?.kind === 'pointer' && previous.source === source ? previous : null) + }} onKeyDown={(event) => { if (event.nativeEvent.isComposing) return if (pending && ADJUST_KEYS.has(event.key)) { @@ -97,13 +213,13 @@ export function EffortSlider({ choices, value, label, currentLabel, formatToolti event.stopPropagation() return } - if (event.key === 'Escape' && gesture !== null) { + if (event.key === 'Escape' && gesture !== null && gesture.kind !== 'hover') { event.preventDefault() event.stopPropagation() - setGesture({ ...gesture, kind: 'cancelled' }) + setGesture({ kind: 'cancelled', source, index }) } else if (ADJUST_KEYS.has(event.key)) { event.stopPropagation() - if (gesture === null) setGesture({ kind: 'keyboard', source, index }) + if (gesture === null || gesture.kind === 'hover') setGesture({ kind: 'keyboard', source, index }) } }} onKeyUp={(event) => { @@ -114,7 +230,15 @@ export function EffortSlider({ choices, value, label, currentLabel, formatToolti }} /> +
diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.tsx b/packages/client/ui-model-selection/src/client/ModelSelect.tsx index 0ae454ffed..c744ba13f5 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.tsx +++ b/packages/client/ui-model-selection/src/client/ModelSelect.tsx @@ -18,6 +18,7 @@ import { import type { PropsLocale, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import type { ModelLabelOwner, ModelMenuPage, ModelSelectInjected } from './slots.ts' import { EffortSlider, type EffortChoice } from './EffortSlider.tsx' +import { effortDisplayName } from './effort-label.ts' import css from './ModelSelect.module.css' import { orderModelProviders } from './provider-order.ts' @@ -105,7 +106,10 @@ export function ModelSelect( ? state.retainedEffort : effectiveEffort === undefined ? t('effort.providerDefault') - : reasoning.efforts.find(level => level.id === effectiveEffort)?.name ?? effectiveEffort + : effortDisplayName({ + id: effectiveEffort, + name: reasoning.efforts.find(level => level.id === effectiveEffort)?.name ?? effectiveEffort, + }, t) const effortChoices = useMemo(() => reasoning === undefined ? [] : [ @@ -115,7 +119,7 @@ export function ModelSelect( ...reasoning.efforts.map((effort: ModelReasoningEffort) => ({ key: `effort:${effort.id}`, effort: effort.id, - label: effort.name, + label: effortDisplayName(effort, t), })), ], [reasoning, t]) const { pending } = state @@ -147,19 +151,14 @@ export function ModelSelect( // Pane switches unmount the focused row; restore focus inside the menu so // keyboard navigation remains available. - const paneFocus = useRef<'drill' | 'model' | 'effort' | ModelMenuPage | null>(null) + const paneFocus = useRef<'drill' | 'model' | ModelMenuPage | null>(null) const previousShowSearch = useRef(showSearch) useEffect(() => { const changedSearchMode = previousShowSearch.current !== showSearch previousShowSearch.current = showSearch const intent = paneFocus.current ?? (changedSearchMode && pane === 'model' ? 'drill' : null) - if (intent === 'effort' && busy) return paneFocus.current = null if (!open || intent === null) return - if (intent === 'effort') { - menuRef.current?.querySelector('input[type="range"]:not([disabled])')?.focus() - return - } if (intent === 'drill') { if (typeof pane === 'object') { const first = menuRef.current?.querySelector('[role="switch"]:not([disabled])') @@ -329,10 +328,12 @@ export function ModelSelect( const settleSelection = (result: Awaited>, origin: 'model' | 'effort'): void => { if (result === undefined) return if (menuRef.current !== null) { - paneFocus.current = origin - if (result.ok) { - setModelReturnFocus(origin === 'model') - setPane('root') + if (origin === 'model') { + paneFocus.current = 'model' + if (result.ok) { + setModelReturnFocus(true) + setPane('root') + } } setSelectionFocus(false) } @@ -492,14 +493,17 @@ export function ModelSelect( : effectiveEffort} label={t('menu.effort')} currentLabel={effortLabel ?? t('effort.providerDefault')} - formatTooltip={effort => t('effort.tooltip', { effort })} + formatLabel={effort => t('effort.tooltip', { effort })} + defaultInfoLabel={t('effort.defaultInfoLabel')} + defaultExplanation={t('effort.defaultExplanation')} disabled={locked} pending={busy} onSelect={chooseEffort} /> )} {renderSlot('conversation.input.model.options', { - locked: locked || busy, + locked, + pending: busy, openPage: (page) => { drill(page) }, dismiss: () => { close() @@ -616,7 +620,8 @@ export function ModelSelect( {typeof pane === 'object' && (
{renderSlot('conversation.input.model.page', { - locked: locked || busy, + locked, + pending: busy, dismiss: () => { close() triggerRef.current?.focus() diff --git a/packages/client/ui-model-selection/src/client/effort-label.ts b/packages/client/ui-model-selection/src/client/effort-label.ts new file mode 100644 index 0000000000..8745ce10eb --- /dev/null +++ b/packages/client/ui-model-selection/src/client/effort-label.ts @@ -0,0 +1,24 @@ +/** Localized display names for standard reasoning levels, without changing provider IDs or custom names. */ +import type { ModelReasoningEffort } from '@deepseek-ai/dsh-api-remotes/client' +import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' + +/** + * Translate standard IDs only when the provider's name repeats that ID, ignoring case. + * @param effort - Provider-owned level ID and display name. + * @param t - The model namespace translator. + * @returns The localized standard name, or the provider's unchanged custom or unknown name. + */ +export function effortDisplayName(effort: Pick, t: PropsLocale<'model'>['t']): string { + if (effort.name.toLowerCase() !== effort.id) return effort.name + switch (effort.id) { + case 'off': return t('effort.off') + case 'minimal': return t('effort.minimal') + case 'low': return t('effort.low') + case 'medium': return t('effort.medium') + case 'high': return t('effort.high') + case 'xhigh': return t('effort.xhigh') + case 'max': return t('effort.max') + // Providers may advertise other IDs; their names remain provider-owned. + default: return effort.name + } +} diff --git a/packages/client/ui-model-selection/src/client/locales.ts b/packages/client/ui-model-selection/src/client/locales.ts index b7b81ff772..5b2e0cd61f 100644 --- a/packages/client/ui-model-selection/src/client/locales.ts +++ b/packages/client/ui-model-selection/src/client/locales.ts @@ -11,6 +11,15 @@ /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { 'effort.tooltip': '推理等级:{effort}', + 'effort.off': '关闭', + 'effort.minimal': '最低', + 'effort.low': '低', + 'effort.medium': '中', + 'effort.high': '高', + 'effort.xhigh': '更高', + 'effort.max': '最高', + 'effort.defaultInfoLabel': '默认推理等级说明', + 'effort.defaultExplanation': '未显式指定推理等级,将使用模型与配置的默认设置;这不代表关闭推理', 'menu.back': '返回', 'provider.account': 'DeepSeek 账号', 'command.label': '模型', @@ -24,7 +33,7 @@ export const zh = { 'menu.aria': '模型与推理等级', 'menu.model': '模型', 'menu.effort': '推理等级', - 'effort.providerDefault': 'Default', + 'effort.providerDefault': '默认', 'status.loading': '正在刷新模型列表…', 'error.action': '模型操作失败:{message}', 'error.sessionInUse': '当前会话已被占用,可能是其他正在运行的 DSH 导致的(如其他 dsh web、桌面端),请退出其他正在运行的 DSH 后重试。', @@ -42,7 +51,16 @@ export type ModelKey = keyof typeof zh /** English dictionary, checked complete against the zh key set. */ export const en = { - 'effort.tooltip': 'Reasoning effort: {effort}', + 'effort.tooltip': 'Effort: {effort}', + 'effort.off': 'Off', + 'effort.minimal': 'Minimal', + 'effort.low': 'Low', + 'effort.medium': 'Medium', + 'effort.high': 'High', + 'effort.xhigh': 'Extra high', + 'effort.max': 'Max', + 'effort.defaultInfoLabel': 'About default reasoning effort', + 'effort.defaultExplanation': 'No reasoning effort is explicitly selected. The model and configuration defaults apply; this does not mean reasoning is off.', 'menu.back': 'Back', 'provider.account': 'DeepSeek Account', 'command.label': 'Model', @@ -71,7 +89,16 @@ export const en = { /** Japanese copy, checked against the English keys. */ export const ja = { - 'effort.tooltip': '推論強度:{effort}', + 'effort.tooltip': '強度:{effort}', + 'effort.off': 'オフ', + 'effort.minimal': '最小', + 'effort.low': '低', + 'effort.medium': '中', + 'effort.high': '高', + 'effort.xhigh': 'より高い', + 'effort.max': '最大', + 'effort.defaultInfoLabel': 'デフォルトの推論強度について', + 'effort.defaultExplanation': '推論強度は明示的に指定されていません。モデルと設定のデフォルト値を使用します。推論をオフにするという意味ではありません。', 'menu.back': '戻る', 'provider.account': 'DeepSeek アカウント', 'command.label': 'モデル', @@ -100,7 +127,16 @@ export const ja = { /** Spanish dictionary, checked against the English keys. */ export const es = { - 'effort.tooltip': 'Esfuerzo de razonamiento: {effort}', + 'effort.tooltip': 'Esfuerzo: {effort}', + 'effort.off': 'Desactivado', + 'effort.minimal': 'Mínimo', + 'effort.low': 'Bajo', + 'effort.medium': 'Medio', + 'effort.high': 'Alto', + 'effort.xhigh': 'Muy alto', + 'effort.max': 'Máximo', + 'effort.defaultInfoLabel': 'Acerca del esfuerzo de razonamiento predeterminado', + 'effort.defaultExplanation': 'No se ha seleccionado explícitamente un esfuerzo de razonamiento. Se aplican los valores predeterminados del modelo y de la configuración; esto no significa que el razonamiento esté desactivado.', 'menu.back': 'Volver', 'provider.account': 'Cuenta DeepSeek', 'command.label': 'modelo', @@ -129,7 +165,16 @@ export const es = { /** French dictionary, checked against the English keys. */ export const fr = { - 'effort.tooltip': 'Effort de raisonnement : {effort}', + 'effort.tooltip': 'Effort : {effort}', + 'effort.off': 'Désactivé', + 'effort.minimal': 'Minimal', + 'effort.low': 'Faible', + 'effort.medium': 'Moyen', + 'effort.high': 'Élevé', + 'effort.xhigh': 'Très élevé', + 'effort.max': 'Maximal', + 'effort.defaultInfoLabel': 'À propos de l’effort de raisonnement par défaut', + 'effort.defaultExplanation': 'Aucun effort de raisonnement n’est explicitement sélectionné. Les valeurs par défaut du modèle et de la configuration s’appliquent ; cela ne signifie pas que le raisonnement est désactivé.', 'menu.back': 'Retour', 'provider.account': 'Compte DeepSeek', 'command.label': 'Modèle', @@ -158,7 +203,16 @@ export const fr = { /** German dictionary, checked against the English keys. */ export const de = { - 'effort.tooltip': 'Denkaufwand: {effort}', + 'effort.tooltip': 'Aufwand: {effort}', + 'effort.off': 'Aus', + 'effort.minimal': 'Minimal', + 'effort.low': 'Niedrig', + 'effort.medium': 'Mittel', + 'effort.high': 'Hoch', + 'effort.xhigh': 'Sehr hoch', + 'effort.max': 'Maximal', + 'effort.defaultInfoLabel': 'Über den standardmäßigen Denkaufwand', + 'effort.defaultExplanation': 'Es ist kein Denkaufwand ausdrücklich ausgewählt. Es gelten die Standardwerte des Modells und der Konfiguration; das bedeutet nicht, dass das Denken deaktiviert ist.', 'menu.back': 'Zurück', 'provider.account': 'DeepSeek-Konto', 'command.label': 'Modell', @@ -187,7 +241,16 @@ export const de = { /** Russian dictionary, checked against the English keys. */ export const ru = { - 'effort.tooltip': 'Уровень рассуждений: {effort}', + 'effort.tooltip': 'Усилие: {effort}', + 'effort.off': 'Выключено', + 'effort.minimal': 'Минимальный', + 'effort.low': 'Низкий', + 'effort.medium': 'Средний', + 'effort.high': 'Высокий', + 'effort.xhigh': 'Очень высокий', + 'effort.max': 'Максимальный', + 'effort.defaultInfoLabel': 'Об уровне рассуждений по умолчанию', + 'effort.defaultExplanation': 'Уровень рассуждений явно не выбран. Применяются значения по умолчанию модели и конфигурации; это не означает, что рассуждения отключены.', 'menu.back': 'Назад', 'provider.account': 'DeepSeek Аккаунт', 'command.label': 'Модель', @@ -216,7 +279,16 @@ export const ru = { /** Portuguese dictionary, checked against the English keys. */ export const pt = { - 'effort.tooltip': 'Esforço de raciocínio: {effort}', + 'effort.tooltip': 'Esforço: {effort}', + 'effort.off': 'Desativado', + 'effort.minimal': 'Mínimo', + 'effort.low': 'Baixo', + 'effort.medium': 'Médio', + 'effort.high': 'Alto', + 'effort.xhigh': 'Muito alto', + 'effort.max': 'Máximo', + 'effort.defaultInfoLabel': 'Sobre o esforço de raciocínio padrão', + 'effort.defaultExplanation': 'Nenhum esforço de raciocínio foi selecionado explicitamente. Aplicam-se os valores padrão do modelo e da configuração; isso não significa que o raciocínio esteja desativado.', 'menu.back': 'Voltar', 'provider.account': 'DeepSeek Conta', 'command.label': 'Modelo', diff --git a/packages/client/ui-model-selection/src/client/slots.ts b/packages/client/ui-model-selection/src/client/slots.ts index 7e62e9710c..cbddc39f66 100644 --- a/packages/client/ui-model-selection/src/client/slots.ts +++ b/packages/client/ui-model-selection/src/client/slots.ts @@ -27,8 +27,10 @@ export interface ModelMenuPage { /** Selection state and feedback shared by menu option entries and detail pages. */ export interface ModelMenuControls { - /** Whether the composer currently refuses selection changes. */ + /** Whether the composer is unavailable for interaction. */ locked: boolean + /** A model or effort selection is saving; block new actions without dimming or removing focus. */ + pending: boolean /** Close the menu and focus its trigger synchronously before opening another overlay. */ dismiss: () => void /** Report a failed selection through the menu owner's persistent toast. */ diff --git a/packages/client/ui-model-selection/tests/effort-label.client.spec.ts b/packages/client/ui-model-selection/tests/effort-label.client.spec.ts new file mode 100644 index 0000000000..682937f730 --- /dev/null +++ b/packages/client/ui-model-selection/tests/effort-label.client.spec.ts @@ -0,0 +1,30 @@ +import { expect, it } from 'vitest' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { effortDisplayName } from '../src/client/effort-label.ts' +import { de, en, es, fr, ja, pt, ru, zh } from '../src/client/locales.ts' + +const standard = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const + +it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }))('localizes canonical effort names in %s without changing IDs', (_locale, dictionary) => { + const t = makeTranslate(dictionary) + for (const id of standard) { + for (const name of [id, id.toUpperCase(), id[0]!.toUpperCase() + id.slice(1)]) { + const effort = { id, name } + expect(effortDisplayName(effort, t)).toBe(dictionary[`effort.${id}`]) + expect(effort.id).toBe(id) + expect(effort.name).toBe(name) + } + } +}) + +it.each([ + { id: 'high', name: 'High budget for code review' }, + { id: 'high', name: ' high' }, + { id: 'high', name: 'High ' }, + { id: 'xhigh', name: 'Extra high' }, + { id: 'standard', name: 'Standard' }, + { id: 'retired', name: 'High' }, + { id: 'High', name: 'High' }, +])('preserves provider spelling for $id / $name', (effort) => { + expect(effortDisplayName(effort, makeTranslate(zh))).toBe(effort.name) +}) diff --git a/packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx b/packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx index 5ff0e2bb20..021b8b1189 100644 --- a/packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx +++ b/packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx @@ -14,17 +14,21 @@ const choices = ['off', 'low', 'high', 'max'].map(effort => ({ key: effort, effo function props(overrides: Partial = {}): EffortSliderProps { return { choices, value: 'high', label: 'Effort', currentLabel: 'high', disabled: false, pending: false, - formatTooltip: effort => `Reasoning effort: ${effort}`, onSelect: vi.fn(), ...overrides, + formatLabel: effort => `Effort: ${effort}`, + defaultInfoLabel: en['effort.defaultInfoLabel'], defaultExplanation: en['effort.defaultExplanation'], + onSelect: vi.fn(), ...overrides, } } function range(): HTMLInputElement { return screen.getByRole('slider') as HTMLInputElement } +function effortLabel(): HTMLElement { + return range().closest('[role="group"]')!.querySelector('[data-effort-label]')! +} -it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }))('localizes the tag tooltip (%s)', (_locale, dictionary) => { - vi.useFakeTimers() +function tooltipLayout() { vi.stubGlobal('matchMedia', (query: string) => ({ - matches: query === '(hover: hover)' || query === '(any-hover: hover)', media: query, onchange: null, + matches: query.includes('hover: hover'), media: query, onchange: null, addEventListener: vi.fn(), removeEventListener: vi.fn(), addListener: vi.fn(), removeListener: vi.fn(), dispatchEvent: () => true, })) vi.stubGlobal('ResizeObserver', class { @@ -32,21 +36,90 @@ it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }))('localizes the tag t unobserve() {} disconnect() {} }) +} + +it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }))('shows the full localized label and default explanation (%s)', (_locale, dictionary) => { + tooltipLayout() const t = makeTranslate(dictionary) + const high = dictionary['effort.high'] + const defaultLabel = dictionary['effort.providerDefault'] const inputProps = props({ - choices: [{ key: 'default', effort: undefined, label: 'Default' }, { key: 'high', effort: 'high', label: 'High' }], - formatTooltip: effort => t('effort.tooltip', { effort }), + choices: [{ key: 'default', effort: undefined, label: defaultLabel }, { key: 'high', effort: 'high', label: high }], + formatLabel: effort => t('effort.tooltip', { effort }), + defaultInfoLabel: dictionary['effort.defaultInfoLabel'], defaultExplanation: dictionary['effort.defaultExplanation'], }) const view = render() - const tag = screen.getByText('High') - expect(tag.tabIndex).toBe(-1) - fireEvent.pointerEnter(tag, { pointerType: 'mouse' }) - act(() => { vi.advanceTimersByTime(500) }) - const tooltip = screen.getByRole('tooltip', { hidden: true }) - expect(tooltip.textContent).toBe(dictionary['effort.tooltip'].replace('{effort}', 'High')) + expect(effortLabel().textContent).toBe(dictionary['effort.tooltip'].replace('{effort}', high)) + expect(effortLabel().tabIndex).toBe(-1) + expect(effortLabel().querySelector('[data-effort-name]')!.textContent).toBe(high) + expect(screen.queryByRole('button')).toBeNull() view.rerender() - expect(tooltip.textContent).toBe(dictionary['effort.tooltip'].replace('{effort}', 'Default')) + expect(effortLabel().textContent).toBe(dictionary['effort.tooltip'].replace('{effort}', defaultLabel)) + expect(effortLabel().querySelector('[data-effort-name]')!.textContent).toBe(defaultLabel) + const info = screen.getByRole('button', { name: dictionary['effort.defaultInfoLabel'] }) + info.focus() + fireEvent.click(info) + expect(screen.getByRole('tooltip', { hidden: true }).textContent).toBe(dictionary['effort.defaultExplanation']) + expect(document.activeElement).toBe(info) expect(inputProps.onSelect).not.toHaveBeenCalled() + fireEvent.keyDown(info, { key: 'Escape' }) + expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() + expect(document.activeElement).toBe(info) +}) + +it.each([ + ['推理等级:高', zh], ['Effort: High', en], ['強度:高', ja], ['Esfuerzo: Alto', es], + ['Effort : Élevé', fr], ['Aufwand: Hoch', de], ['Усилие: Высокий', ru], ['Esforço: Alto', pt], +] as const)('uses a compact localized caption: %s', (expected, dictionary) => { + const t = makeTranslate(dictionary) + render( t('effort.tooltip', { effort }), + })} />) + expect(effortLabel().textContent).toBe(expected) +}) + +it('protects the final effort name while preserving repeated text in the formatted prefix', () => { + render( `${effort} policy: ${effort}` })} />) + const label = effortLabel() + const name = label.querySelector('[data-effort-name]')! + expect(label.textContent).toBe('high policy: high') + expect(name.textContent).toBe('high') + expect(name.previousElementSibling!.textContent).toBe('high policy: ') + expect(range().getAttribute('aria-valuetext')).toBe('high') +}) + +it('only repeats the full label in a tooltip when the label is clipped', () => { + tooltipLayout() + vi.useFakeTimers() + render() + const label = effortLabel() + fireEvent.pointerEnter(label, { pointerType: 'mouse' }) + act(() => { vi.advanceTimersByTime(500) }) + expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() + fireEvent.pointerLeave(label, { pointerType: 'mouse' }) + Object.defineProperty(label, 'scrollWidth', { configurable: true, value: 200 }) + Object.defineProperty(label, 'clientWidth', { configurable: true, value: 80 }) + fireEvent.pointerEnter(label, { pointerType: 'mouse' }) + act(() => { vi.advanceTimersByTime(500) }) + expect(screen.getByRole('tooltip', { hidden: true }).textContent).toBe('Effort: high') +}) + +it('closes default information on a second activation or Tab without selecting an effort', () => { + tooltipLayout() + const inputProps = props({ choices: [{ key: 'default', effort: undefined, label: 'Default' }, ...choices], value: undefined }) + render() + const info = screen.getByRole('button', { name: en['effort.defaultInfoLabel'] }) + info.focus() + fireEvent.click(info) + expect(screen.getByRole('tooltip', { hidden: true })).toBeTruthy() + fireEvent.click(info) + expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() + fireEvent.click(info) + fireEvent.keyDown(info, { key: 'Tab' }) + expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() + expect(inputProps.onSelect).not.toHaveBeenCalled() + expect(range().value).toBe('0') }) it('shows exact advertised stops and the selected value', () => { @@ -56,7 +129,8 @@ it('shows exact advertised stops and the selected value', () => { expect(range().getAttribute('aria-valuetext')).toBe('high') expect(range().min).toBe('0') expect(range().step).toBe('1') - expect(screen.getByText('high').tabIndex).toBe(-1) + expect(effortLabel().textContent).toBe('Effort: high') + expect(effortLabel().tabIndex).toBe(-1) expect(screen.queryByRole('button')).toBeNull() }) @@ -183,7 +257,7 @@ it('does not pretend an unknown stored effort matches the first supported stop', render() expect(range().disabled).toBe(true) expect(range().getAttribute('aria-valuetext')).toBe('retired') - expect(screen.getByText('retired')).toBeTruthy() + expect(effortLabel().textContent).toBe('Effort: retired') expect(screen.queryByRole('button')).toBeNull() }) @@ -193,6 +267,160 @@ it.each([{ levels: [] }, { levels: choices.slice(0, 1) }])('does not offer dragg expect(range().max).toBe('0') }) +function motionSetup() { + vi.stubGlobal('matchMedia', (query: string) => ({ + matches: query === '(hover: hover) and (pointer: fine)', media: query, onchange: null, + addEventListener: vi.fn(), removeEventListener: vi.fn(), addListener: vi.fn(), removeListener: vi.fn(), dispatchEvent: () => true, + })) + const inputProps = props({ value: 'off', currentLabel: 'off' }) + const view = render() + const input = range() + const thumb = view.container.querySelector('[data-effort-thumb]')! + const scale = view.container.querySelector('[data-effort-thumb-scale]')! + vi.spyOn(input, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 220, 40)) + vi.spyOn(thumb, 'getBoundingClientRect').mockImplementation(() => new DOMRect(Number(input.value) / 3 * 200, 10, 20, 20)) + const pointer = (type: string, x: number, pointerType = 'mouse') => fireEvent(input, + Object.assign(new MouseEvent(type, { bubbles: true, cancelable: true, clientX: x, clientY: 20, button: 0 }), + { pointerType, pointerId: 1, isPrimary: true })) + return { ...view, input, inputProps, thumb, scale, pointer } +} + +it('keeps the visual track and thumb inert while the native range owns interaction', () => { + const view = motionSetup() + expect(screen.getAllByRole('slider')).toHaveLength(1) + expect(view.thumb.closest('[aria-hidden="true"]')).toBeTruthy() + expect(view.container.querySelector('[data-effort-fill]')!.closest('[aria-hidden="true"]')).toBeTruthy() + expect(view.thumb.tabIndex).toBe(-1) + expect(view.scale.tabIndex).toBe(-1) + expect(screen.queryByRole('button')).toBeNull() +}) + +it('hovers one tick in its 16px target without selecting and does not retain touch hover', () => { + const view = motionSetup() + view.pointer('pointermove', 10) + expect(view.scale.hasAttribute('data-expanded')).toBe(true) + view.pointer('pointermove', 10 + 200 / 3 + 7) + expect(view.scale.hasAttribute('data-expanded')).toBe(false) + expect(view.container.querySelectorAll('[data-effort-tick][data-hovered]')).toHaveLength(1) + expect(view.container.querySelector('[data-effort-tick="1"]')!.hasAttribute('data-hovered')).toBe(true) + view.pointer('pointermove', 10 + 200 / 3 + 9) + expect(view.container.querySelector('[data-hovered]')).toBeNull() + view.pointer('pointermove', 10) + view.pointer('pointermove', 10, 'touch') + expect(view.scale.hasAttribute('data-expanded')).toBe(false) + expect(view.container.querySelector('[data-hovered]')).toBeNull() + expect(view.input.value).toBe('0') + expect(view.inputProps.onSelect).not.toHaveBeenCalled() +}) + +it.each(['pointercancel', 'blur', 'Escape'])('cancels motion decoration and the native preview on %s', (cancel) => { + const view = motionSetup() + view.pointer('pointerdown', 16) + view.pointer('pointermove', 60) + fireEvent.change(view.input, { target: { value: '1' } }) + expect(view.input.parentElement!.hasAttribute('data-dragging')).toBe(true) + expect(view.container.querySelector('[data-hovered]')).toBeNull() + if (cancel === 'Escape') fireEvent.keyDown(view.input, { key: 'Escape' }) + else if (cancel === 'blur') fireEvent.blur(view.input) + else view.pointer(cancel, 60) + view.pointer('pointerup', 60) + expect(view.input.parentElement!.hasAttribute('data-dragging')).toBe(false) + expect(view.input.value).toBe('0') + expect(view.inputProps.onSelect).not.toHaveBeenCalled() +}) + +it('keeps a native pointer gesture when focus moves to an ancestor before the first move', () => { + const view = motionSetup() + act(() => { + view.pointer('pointerdown', 16) + fireEvent.blur(view.input, { relatedTarget: view.input.parentElement }) + }) + expect(view.scale.hasAttribute('data-expanded')).toBe(true) + view.pointer('pointermove', 76) + fireEvent.change(view.input, { target: { value: '1' } }) + expect(view.input.parentElement!.hasAttribute('data-dragging')).toBe(true) + expect(view.inputProps.onSelect).not.toHaveBeenCalled() + view.pointer('pointerup', 76) + expect(view.inputProps.onSelect).toHaveBeenCalledExactlyOnceWith('low') +}) + +it('restores range focus before submitting a valid native pointer release', () => { + const view = motionSetup() + view.input.focus() + view.pointer('pointerdown', 16) + const ancestor = view.input.parentElement! + ancestor.tabIndex = -1 + act(() => { ancestor.focus() }) + fireEvent.change(view.input, { target: { value: '1' } }) + vi.mocked(view.inputProps.onSelect).mockImplementation(() => { expect(document.activeElement).toBe(view.input) }) + view.pointer('pointerup', 76) + expect(view.inputProps.onSelect).toHaveBeenCalledExactlyOnceWith('low') +}) + +it('does not steal outside focus when a cancelled pointer later releases', () => { + const view = motionSetup() + view.input.focus() + view.pointer('pointerdown', 16) + fireEvent.change(view.input, { target: { value: '1' } }) + const outside = document.createElement('button') + view.container.append(outside) + act(() => { outside.focus() }) + view.pointer('pointerup', 76) + expect(document.activeElement).toBe(outside) + expect(view.inputProps.onSelect).not.toHaveBeenCalled() +}) + +it.each(['null', 'outside', 'keyboard-ancestor'])('still cancels a preview on %s focus loss', (kind) => { + const view = motionSetup() + if (kind === 'keyboard-ancestor') fireEvent.keyDown(view.input, { key: 'End' }) + else view.pointer('pointerdown', 16) + fireEvent.change(view.input, { target: { value: '1' } }) + const outside = document.createElement('button') + view.container.append(outside) + fireEvent.blur(view.input, { + relatedTarget: kind === 'keyboard-ancestor' ? view.input.parentElement : kind === 'outside' ? outside : null, + }) + if (kind === 'keyboard-ancestor') fireEvent.keyUp(view.input, { key: 'End' }) + else view.pointer('pointerup', 76) + expect(view.input.value).toBe('0') + expect(view.input.parentElement!.hasAttribute('data-dragging')).toBe(false) + expect(view.inputProps.onSelect).not.toHaveBeenCalled() +}) + +it('retains thumb hover through a pending save without accepting more values', () => { + const view = motionSetup() + view.pointer('pointerdown', 10) + fireEvent.change(view.input, { target: { value: '1' } }) + view.pointer('pointerup', 10 + 200 / 3) + expect(view.inputProps.onSelect).toHaveBeenCalledExactlyOnceWith('low') + expect(view.scale.hasAttribute('data-expanded')).toBe(true) + view.rerender() + expect(view.scale.hasAttribute('data-expanded')).toBe(true) + view.pointer('pointermove', 10 + 200 / 3) + expect(view.scale.hasAttribute('data-expanded')).toBe(true) + fireEvent.change(view.input, { target: { value: '3' } }) + expect(view.input.value).toBe('1') + expect(view.inputProps.onSelect).toHaveBeenCalledTimes(1) + view.rerender() + expect(view.scale.hasAttribute('data-expanded')).toBe(true) +}) + +it('clears hover and motion when locked or when the advertised catalog changes', () => { + const view = motionSetup() + view.pointer('pointermove', 10) + expect(view.scale.hasAttribute('data-expanded')).toBe(true) + view.rerender() + expect(view.scale.hasAttribute('data-expanded')).toBe(false) + expect(view.input.disabled).toBe(true) + view.pointer('pointermove', 10) + expect(view.scale.hasAttribute('data-expanded')).toBe(false) + view.rerender() + view.pointer('pointermove', 10) + view.rerender() + expect(view.scale.hasAttribute('data-expanded')).toBe(false) + expect(view.inputProps.onSelect).not.toHaveBeenCalled() +}) + it('keeps the pending target focusable while blocking pointer, keyboard and direct changes', () => { const inputProps = props({ value: 'max', pending: true }) render() diff --git a/packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx b/packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx index 7c3ae849d4..0dd538e1ca 100644 --- a/packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx +++ b/packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx @@ -17,16 +17,17 @@ beforeEach(() => { else Object.defineProperty(Element.prototype, 'scrollIntoView', descriptor) }) }) -afterEach(cleanup) +afterEach(() => { cleanup(); vi.unstubAllGlobals() }) -function setup(count = 2, hasReasoning = true) { +function setup(count = 2, hasReasoning = true, providerDefault = false) { const select = vi.fn(async () => ({ ok: true as const, value: undefined })) const toggle = vi.fn() const directory = createSnapshotStore({ current: { provider: 'sample', model: 'model-1' }, routable: true, groups: [{ id: 'sample', name: 'Sample', models: Array.from({ length: count }, (_, index) => ({ id: `model-${index + 1}`, name: `Model ${index + 1}`, - ...hasReasoning ? { reasoning: { efforts: [{ id: 'low', name: 'Low' }, { id: 'high', name: 'High' }], defaultEffort: 'high' } } : {}, + ...hasReasoning ? { reasoning: { efforts: [{ id: 'low', name: 'Low' }, { id: 'high', name: 'High' }], + ...providerDefault ? {} : { defaultEffort: 'high' } } } : {}, })) }], failures: [], status: 'ready', pending: null, error: null, }) const renderSlot: ComponentProps['renderSlot'] = (name, owner: object, options) => { @@ -34,10 +35,16 @@ function setup(count = 2, hasReasoning = true) { const controls = owner as OwnerOf<'conversation.input.model.options'> return <> - + } - if (name === 'conversation.input.model.page') return + if (name === 'conversation.input.model.page') { + const controls = owner as OwnerOf<'conversation.input.model.page'> + return + } return options?.fallback ?? null } render(<> { + vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} }) + const view = setup(2, true, true) + tab() + expect(document.activeElement).toBe(view.model()) + tab() + const info = screen.getByRole('button', { name: en['effort.defaultInfoLabel'] }) + expect(document.activeElement).toBe(info) + fireEvent.click(info) + expect(screen.getByRole('tooltip', { hidden: true }).textContent).toBe(en['effort.defaultExplanation']) + fireEvent.keyDown(info, { key: 'Escape' }) + expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() + expect(screen.getByRole('menu')).toBeTruthy() + expect(document.activeElement).toBe(info) + fireEvent.click(info) + tab() + const slider = screen.getByRole('slider') + expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() + expect(document.activeElement).toBe(slider) + tab() + expect(document.activeElement).toBe(view.team()) + tab(true) + expect(document.activeElement).toBe(slider) + tab(true) + expect(document.activeElement).toBe(info) + expect(view.select).not.toHaveBeenCalled() + expect(view.toggle).not.toHaveBeenCalled() +}) + +it('removes only the default information Tab stop when the selection changes', () => { + vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} }) + const view = setup(2, true, true) + const info = screen.getByRole('button', { name: en['effort.defaultInfoLabel'] }) + info.focus() + act(() => { view.directory.update((snapshot) => { + snapshot.current = { provider: 'sample', model: 'model-1', reasoningEffort: 'high' } + }) }) + const slider = screen.getByRole('slider') + expect(screen.queryByRole('button', { name: en['effort.defaultInfoLabel'] })).toBeNull() + expect(document.activeElement).toBe(slider) + tab(true) + expect(document.activeElement).toBe(view.model()) + act(() => { view.directory.update((snapshot) => { + snapshot.current = { provider: 'sample', model: 'model-1' } + }) }) + tab() + expect(document.activeElement).toBe(screen.getByRole('button', { name: en['effort.defaultInfoLabel'] })) + expect(view.select).not.toHaveBeenCalled() +}) + +it('keeps a pending contributed entry in Tab order without allowing navigation', () => { + const view = setup() + tab(); tab(); tab() + const team = view.team() + expect(document.activeElement).toBe(team) + act(() => { view.directory.update((snapshot) => { + snapshot.status = 'selecting' + snapshot.pending = { provider: 'sample', model: 'model-1', reasoningEffort: 'low' } + }) }) + expect(view.team()).toBe(team) + expect(team.hasAttribute('disabled')).toBe(false) + expect(team.getAttribute('aria-disabled')).toBe('true') + expect(document.activeElement).toBe(team) + fireEvent.click(team) + expect(screen.queryByRole('switch')).toBeNull() + tab(true) + expect(document.activeElement).toBe(screen.getByRole('slider')) + tab() + expect(document.activeElement).toBe(team) + expect(view.select).not.toHaveBeenCalled() + expect(view.toggle).not.toHaveBeenCalled() +}) + it('Shift+Tab from the first root control returns to its trigger instead of activating it', () => { const view = setup() tab() 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 af1861f0a8..fe2cbdcfa9 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 @@ -223,14 +223,16 @@ describe('ModelSelect reasoning effort', () => { />) const trigger = screen.getByRole('button', { - name: '选择模型,当前 DeepSeek-V4-Flash,推理等级 High', + name: '选择模型,当前 DeepSeek-V4-Flash,推理等级 高', }) fireEvent.click(trigger) const efforts = within(screen.getByRole('group', { name: '推理等级' })) expect(efforts.queryByRole('button')).toBeNull() expect(efforts.getByRole('slider').getAttribute('max')).toBe('2') - expect(efforts.getByRole('slider', { name: '推理等级' }).getAttribute('aria-valuetext')).toBe('High') - expect(efforts.getByText('High').tabIndex).toBe(-1) + expect(efforts.getByRole('slider', { name: '推理等级' }).getAttribute('aria-valuetext')).toBe('高') + const label = screen.getByRole('group', { name: '推理等级' }).querySelector('[data-effort-label]')! + expect(label.textContent).toBe('推理等级:高') + expect(label.tabIndex).toBe(-1) expect(screen.queryByRole('menuitem', { name: /推理等级/ })).toBeNull() expect(screen.queryByText('Largest budget')).toBeNull() @@ -243,7 +245,7 @@ describe('ModelSelect reasoning effort', () => { model: 'deepseek-v4-flash', reasoningEffort: 'max', }) - expect(trigger.getAttribute('aria-label')).toBe('选择模型,当前 DeepSeek-V4-Flash,推理等级 Max') + expect(trigger.getAttribute('aria-label')).toBe('选择模型,当前 DeepSeek-V4-Flash,推理等级 最高') expect(document.activeElement).toBe(slider) expect(screen.getByRole('menu')).toBeTruthy() }) @@ -272,12 +274,13 @@ describe('ModelSelect reasoning effort', () => { />) fireEvent.click(screen.getByRole('button', { - name: '选择模型,当前 Model,推理等级 Default', + name: '选择模型,当前 Model,推理等级 默认', })) const efforts = within(screen.getByRole('group', { name: '推理等级' })) - expect(efforts.queryByRole('button')).toBeNull() + expect(efforts.getByRole('button', { name: '默认推理等级说明' })).toBeTruthy() + expect(screen.getByRole('group', { name: '推理等级' }).querySelector('[data-effort-label]')!.textContent).toBe('推理等级:默认') expect(efforts.getByRole('slider').getAttribute('max')).toBe('1') - expect(efforts.getByRole('slider').getAttribute('aria-valuetext')).toBe('Default') + expect(efforts.getByRole('slider').getAttribute('aria-valuetext')).toBe('默认') }) it('submits the Default stop by omitting effort instead of sending a display label', async () => { @@ -308,8 +311,8 @@ describe('ModelSelect reasoning effort', () => { fireEvent.pointerDown(slider, { pointerId: 1 }) fireEvent.change(slider, { target: { value: '0' } }) fireEvent.change(slider, { target: { value: '2' } }) - expect(slider.getAttribute('aria-valuetext')).toBe('Max') - expect(trigger.getAttribute('aria-label')).toBe('选择模型,当前 DeepSeek-V4-Flash,推理等级 High') + expect(slider.getAttribute('aria-valuetext')).toBe('最高') + expect(trigger.getAttribute('aria-label')).toBe('选择模型,当前 DeepSeek-V4-Flash,推理等级 高') expect(select).not.toHaveBeenCalled() fireEvent.pointerUp(slider, { pointerId: 1 }) expect(select).toHaveBeenCalledExactlyOnceWith({ provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' }) @@ -329,7 +332,7 @@ describe('ModelSelect reasoning effort', () => { expect((await screen.findByRole('alert')).textContent).toContain('effort unavailable') expect(screen.getByRole('menu')).toBeTruthy() const slider = screen.getByRole('slider', { name: '推理等级' }) - expect(slider.getAttribute('aria-valuetext')).toBe('High') + expect(slider.getAttribute('aria-valuetext')).toBe('高') expect(slider.hasAttribute('disabled')).toBe(false) expect(document.activeElement).toBe(slider) await act(async () => { fireEvent.change(slider, { target: { value: '0' } }) }) @@ -403,7 +406,7 @@ describe('ModelSelect reasoning effort', () => { directory.set(state()) await waitFor(() => { expect(screen.getByRole('button', { - name: '选择模型,当前 DeepSeek-V4-Flash,推理等级 High', + name: '选择模型,当前 DeepSeek-V4-Flash,推理等级 高', })).toBeTruthy() }) }) @@ -519,7 +522,7 @@ describe('ModelSelect reasoning effort', () => { expect(slider.hasAttribute('disabled')).toBe(false) expect(slider.getAttribute('aria-disabled')).toBe('true') expect(slider.getAttribute('aria-busy')).toBe('true') - expect(slider.getAttribute('aria-valuetext')).toBe('Max') + expect(slider.getAttribute('aria-valuetext')).toBe('最高') expect(document.activeElement).toBe(slider) fireEvent.change(slider, { target: { value: '0' } }) expect(select).toHaveBeenCalledExactlyOnceWith({ @@ -532,10 +535,38 @@ describe('ModelSelect reasoning effort', () => { expect(screen.getByRole('menu')).toBeTruthy() expect(trigger.getAttribute('aria-busy')).toBe('false') expect(slider.getAttribute('aria-disabled')).toBe('false') - expect(slider.getAttribute('aria-valuetext')).toBe('Max') + expect(slider.getAttribute('aria-valuetext')).toBe('最高') expect(document.activeElement).toBe(slider) }) + it('keeps the browsed model page and search focus when an effort save finishes', async () => { + const groups = modelGroups(5) + const directory = createSnapshotStore(state({ groups })) + const pending = Promise.withResolvers<{ ok: true; value: undefined }>() + onTestFinished(async () => { await act(async () => { pending.resolve({ ok: true, value: undefined }) }) }) + const select = vi.fn((selection: ModelSelection) => { + directory.set(state({ groups, status: 'selecting', pending: selection })) + return pending.promise + }) + render() + fireEvent.click(screen.getByRole('button', { name: /选择模型/ })) + const slider = screen.getByRole('slider') + slider.focus() + fireEvent.change(slider, { target: { value: '2' } }) + fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) + const search = screen.getByRole('searchbox') + expect(document.activeElement).toBe(search) + await act(async () => { + directory.set(state({ groups, current: { provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' } })) + pending.resolve({ ok: true, value: undefined }) + }) + expect(screen.getByRole('searchbox')).toBe(search) + expect(document.activeElement).toBe(search) + expect(screen.getByRole('group', { name: '模型' })).toBeTruthy() + expect(select).toHaveBeenCalledExactlyOnceWith({ provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' }) + }) + it('keeps transient focus loss inside the menu but closes on a known outside focus target', () => { render(<>) @@ -695,7 +726,7 @@ describe('ModelSelect keyboard walk', () => { expect(document.activeElement).toBe(focused) if (kind === 'inline effort') { expect(fireEvent.mouseDown(screen.getByRole('slider'))).toBe(true) - expect(screen.getByRole('slider').getAttribute('aria-valuetext')).toBe('High') + expect(screen.getByRole('slider').getAttribute('aria-valuetext')).toBe('高') } else { fireEvent.keyDown(focused!, { key: 'Escape' }) expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) @@ -727,7 +758,7 @@ describe('ModelSelect keyboard walk', () => { fireEvent.keyDown(slider, { key: 'End' }) // jsdom does not perform the native range value change for a keyboard event. fireEvent.change(slider, { target: { value: '2' } }) - expect(slider.getAttribute('aria-valuetext')).toBe('Max') + expect(slider.getAttribute('aria-valuetext')).toBe('最高') expect(select).not.toHaveBeenCalled() fireEvent.keyUp(slider, { key: 'End' }) expect(select).toHaveBeenCalledExactlyOnceWith({ @@ -782,13 +813,13 @@ describe('ModelSelect keyboard walk', () => { directory={createSnapshotStore(state({ current: { provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' } }))} load={vi.fn()} resolveText={resolveText} select={select} t={t} />) fireEvent.click(screen.getByRole('button', { name: /选择模型/ })) - expect(screen.getByRole('slider').getAttribute('aria-valuetext')).toBe('Max') + expect(screen.getByRole('slider').getAttribute('aria-valuetext')).toBe('最高') fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) expect(screen.queryByRole('slider')).toBeNull() fireEvent.keyDown(document.activeElement!, { key: 'Escape' }) expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) - expect(screen.getByRole('slider').getAttribute('aria-valuetext')).toBe('Max') - expect(screen.queryByRole('button', { name: 'Max' })).toBeNull() + expect(screen.getByRole('slider').getAttribute('aria-valuetext')).toBe('最高') + expect(screen.queryByRole('button', { name: '推理等级:最高' })).toBeNull() expect(select).not.toHaveBeenCalled() }) @@ -1226,11 +1257,11 @@ it('restores the account model name after login without changing the saved route const directory = createSnapshotStore(state({ current: selected, groups, retainedEffort: 'High' })) render() - expect(screen.getByRole('button', { name: /选择模型,当前/ }).textContent).toBe('DeepSeek FlashHigh') + expect(screen.getByRole('button', { name: /选择模型,当前/ }).textContent).toBe('DeepSeek Flash高') act(() => { directory.update((snapshot) => { snapshot.groups = []; snapshot.routable = false }) }) expect(screen.getByRole('button', { name: '请选择模型' }).textContent).toBe('请选择模型') act(() => { directory.update((snapshot) => { snapshot.groups = groups; snapshot.routable = true }) }) - expect(screen.getByRole('button', { name: /选择模型,当前/ }).textContent).toBe('DeepSeek FlashHigh') + expect(screen.getByRole('button', { name: /选择模型,当前/ }).textContent).toBe('DeepSeek Flash高') expect(directory.getSnapshot().current).toEqual(selected) }) @@ -1239,11 +1270,14 @@ describe('ModelSelect contributed pages', () => { function mountPage(locked = false, withSwitch = true) { const toggle = vi.fn() const select = vi.fn() + const owners = vi.fn((_name: string, _owner: object) => {}) const renderSlot: ComponentProps['renderSlot'] = (name, owner: object, options) => { + owners(name, owner) if (name === 'conversation.input.model.options') { const controls = owner as OwnerOf<'conversation.input.model.options'> return } @@ -1253,7 +1287,8 @@ describe('ModelSelect contributed pages', () => { return <>

用于解释该设置的完整说明

{withSwitch && } + disabled={controls.locked} aria-disabled={controls.locked || controls.pending} aria-busy={controls.pending} + onClick={() => { if (!controls.pending) toggle() }}>启用示例设置} @@ -1265,7 +1300,7 @@ describe('ModelSelect contributed pages', () => { load={vi.fn()} resolveText={resolveText} select={select} t={t} renderSlot={renderSlot} />) const trigger = screen.getByRole('button', { name: /^选择模型/ }) if (!locked) fireEvent.click(trigger) - return { directory, view, trigger, renderSlot, toggle, select } + return { directory, view, trigger, renderSlot, owners, toggle, select } } it('opens only the keyed detail controls and returns to the invoking entry with Escape', () => { @@ -1320,12 +1355,30 @@ describe('ModelSelect contributed pages', () => { expect(screen.getByRole('menu')).toBeTruthy() }) - it('passes pending selection locking into the keyed page while keeping Escape navigation available', () => { - const { directory, toggle } = mountPage() - fireEvent.click(screen.getByRole('menuitem', { name: '设置 关' })) - act(() => { directory.set(state({ status: 'selecting', pending: { provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' } })) }) + it('passes model pending separately from a genuine lock into both contributed slots', () => { + const { directory, toggle, owners } = mountPage() + const entry = screen.getByRole('menuitem', { name: '设置 关' }) + entry.focus() + owners.mockClear() + const selecting = state({ status: 'selecting', pending: { + provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max', + } }) + act(() => { directory.set(selecting) }) + expect(owners).toHaveBeenCalledWith('conversation.input.model.options', expect.objectContaining({ locked: false, pending: true })) + expect(entry.hasAttribute('disabled')).toBe(false) + expect(entry.getAttribute('aria-disabled')).toBe('true') + expect(document.activeElement).toBe(entry) + fireEvent.click(entry) + expect(screen.queryByRole('switch')).toBeNull() + act(() => { directory.set(state()) }) + fireEvent.click(entry) const switchButton = screen.getByRole('switch', { name: '启用示例设置' }) - expect(switchButton.hasAttribute('disabled')).toBe(true) + owners.mockClear() + act(() => { directory.set(selecting) }) + expect(owners).toHaveBeenCalledWith('conversation.input.model.page', expect.objectContaining({ locked: false, pending: true })) + expect(switchButton.hasAttribute('disabled')).toBe(false) + expect(switchButton.getAttribute('aria-disabled')).toBe('true') + expect(document.activeElement).toBe(switchButton) fireEvent.click(switchButton) expect(toggle).not.toHaveBeenCalled() fireEvent.keyDown(switchButton, { key: 'Escape' }) diff --git a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts index 83879bec56..18d5b71615 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -1545,7 +1545,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.label\', () => ctx.slots.register(\n { name: \'conversation.input.model.label\' },\n ({ provider, model }) => React.createElement(\'span\', { title: provider.name }, model.name),\n ))\n },\n}', - source: 'packages/client/ui-model-selection/src/client/slots.ts:70', + source: 'packages/client/ui-model-selection/src/client/slots.ts:72', }, { key: 'conversation.input.model.options', @@ -1574,7 +1574,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ }, ], ownerProps: [ - '/** Selection state and feedback shared by menu option entries and detail pages. */\nexport interface ModelMenuControls {\n /** Whether the composer currently refuses selection changes. */\n locked: boolean\n /** Close the menu and focus its trigger synchronously before opening another overlay. */\n dismiss: () => void\n /** Report a failed selection through the menu owner\'s persistent toast. */\n reportFailure: (message: string) => void\n}', + '/** Selection state and feedback shared by menu option entries and detail pages. */\nexport interface ModelMenuControls {\n /** Whether the composer is unavailable for interaction. */\n locked: boolean\n /** A model or effort selection is saving; block new actions without dimming or removing focus. */\n pending: boolean\n /** Close the menu and focus its trigger synchronously before opening another overlay. */\n dismiss: () => void\n /** Report a failed selection through the menu owner\'s persistent toast. */\n reportFailure: (message: string) => void\n}', '/** A keyed contribution displayed as a second page of the model menu. */\nexport interface ModelMenuPage {\n /** Registration key in conversation.input.model.page; also marks its root button\'s data-model-menu-page. */\n key: string\n /** Localized accessible name of the detail page. */\n title: string\n}', ], ownerPropsReferences: [], @@ -1608,7 +1608,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.options\', () => ctx.slots.register(\n { name: \'conversation.input.model.options\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-model-selection/src/client/slots.ts:41', + source: 'packages/client/ui-model-selection/src/client/slots.ts:43', }, { key: 'conversation.input.model.page', @@ -1625,7 +1625,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ }, ], ownerProps: [ - '/** Selection state and feedback shared by menu option entries and detail pages. */\nexport interface ModelMenuControls {\n /** Whether the composer currently refuses selection changes. */\n locked: boolean\n /** Close the menu and focus its trigger synchronously before opening another overlay. */\n dismiss: () => void\n /** Report a failed selection through the menu owner\'s persistent toast. */\n reportFailure: (message: string) => void\n}', + '/** Selection state and feedback shared by menu option entries and detail pages. */\nexport interface ModelMenuControls {\n /** Whether the composer is unavailable for interaction. */\n locked: boolean\n /** A model or effort selection is saving; block new actions without dimming or removing focus. */\n pending: boolean\n /** Close the menu and focus its trigger synchronously before opening another overlay. */\n dismiss: () => void\n /** Report a failed selection through the menu owner\'s persistent toast. */\n reportFailure: (message: string) => void\n}', ], ownerPropsReferences: [], standardProps: [ @@ -1658,7 +1658,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.page\', () => ctx.slots.register(\n { name: \'conversation.input.model.page\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-model-selection/src/client/slots.ts:50', + source: 'packages/client/ui-model-selection/src/client/slots.ts:52', }, { key: 'conversation.input.overlay', From 0dd0bd18cdb3b81e023e9764dd04abaf14492cf9 Mon Sep 17 00:00:00 2001 From: Shigma Date: Thu, 5 Nov 2026 16:26:40 +0800 Subject: [PATCH 004/450] refactor(cordis): route Include-dialect YAML through Include exports --- apps/cli/tests/built-bin.e2e.ts | 5 +-- .../tests/dump-config-schema.expected.e2e.ts | 5 +-- .../tests/lazy-search-startup.compat.spec.ts | 12 ++--- apps/cli/tests/windows-shell.spec.ts | 5 +-- apps/web/tests/client-ui-stats-panel.e2e.ts | 5 +-- apps/web/tests/scaffold.ts | 5 +-- apps/web/tests/schedule-after.e2e.ts | 7 ++- apps/web/tests/settings-import.e2e.ts | 5 +-- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- packages/boot/app-boot/package.json | 2 - .../app-boot/src/compatibility-preflight.ts | 5 +-- .../app-boot/src/config-schema/collect.ts | 8 ++-- packages/boot/app-boot/src/index.ts | 16 ++----- .../tests/compatibility-preflight.spec.ts | 5 +-- .../boot/app-boot/tests/config-dump.spec.ts | 9 ++-- packages/boot/config-editor/package.json | 4 +- packages/boot/config-editor/src/index.ts | 5 +-- packages/bundle/acp-app/tests/acp-app.spec.ts | 8 +--- packages/bundle/base/tests/base.spec.ts | 13 ++---- packages/bundle/sdk-app/tests/sdk-app.spec.ts | 8 +--- .../sdk-minimal/tests/sdk-minimal.spec.ts | 8 +--- packages/experimental/cua-bundle/package.json | 1 - .../cua-bundle/tests/platform.spec.ts | 7 +-- .../inspector-profile/package.json | 3 +- .../inspector-profile/tests/profile.spec.ts | 7 +-- .../personalized-recommendations/package.json | 1 - .../tests/bundle.spec.ts | 11 ++--- .../webworker-packer/package.json | 2 - .../experimental/webworker-packer/src/pack.ts | 7 ++- .../tests/profile-image.spec.ts | 5 +-- .../preset/agent-preset-registry/package.json | 6 +-- .../preset/agent-preset-registry/src/index.ts | 5 +-- packages/preset/agent-preset/package.json | 4 +- .../preset/agent-preset/tests/skills.spec.ts | 5 +-- .../settings/tests/profile-composition.ts | 7 ++- .../test-support/client-runtime/package.json | 2 - .../src/assembly/bundle-roster.ts | 7 ++- .../session-snapshot/src/launcher.ts | 7 ++- pnpm-lock.yaml | 45 ------------------- scripts/cordis-entry-yaml.spec.ts | 39 ++++++++++++++++ scripts/cordis-yaml.ts | 14 +----- vendor/README.md | 2 +- vendor/include/README.md | 2 +- vendor/include/src/index.ts | 44 ++++++++++++++++-- 45 files changed, 161 insertions(+), 216 deletions(-) create mode 100644 scripts/cordis-entry-yaml.spec.ts diff --git a/apps/cli/tests/built-bin.e2e.ts b/apps/cli/tests/built-bin.e2e.ts index 1c8765d268..acb6e4ab37 100644 --- a/apps/cli/tests/built-bin.e2e.ts +++ b/apps/cli/tests/built-bin.e2e.ts @@ -13,9 +13,8 @@ import { } from '@agentclientprotocol/sdk' import { withFileLock, writeFileAtomic } from '@deepseek-ai/dsh-atomic-write' import { startMockLlmServer } from '@deepseek-ai/dsh-llm-mock-server' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' import { execa } from 'execa' -import * as yaml from 'js-yaml' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { testProfileResolution } from './profiles/headless/tests/profile-resolution.ts' @@ -1259,7 +1258,7 @@ describe.skipIf(!existsSync(dshBin))('dsh BUILT bin (node lib/bin.js, no tsx)', ) expect(code).toBe(0) expect(stderr).toBe('') - const rows = yaml.load(stdout, { schema: entryListSchema }) as Array<{ id?: string; name?: string }> + const rows = parseEntryYaml(stdout) as Array<{ id?: string; name?: string }> expect(rows.map(row => [row.id, row.name])).toEqual([ ['sdk-app-startup', '@deepseek-ai/dsh-sdk-app'], ['sdk-jsonrpc-server', '@deepseek-ai/dsh-sdk-jsonrpc-server'], diff --git a/apps/cli/tests/dump-config-schema.expected.e2e.ts b/apps/cli/tests/dump-config-schema.expected.e2e.ts index d481c9bd2a..b6472adabb 100644 --- a/apps/cli/tests/dump-config-schema.expected.e2e.ts +++ b/apps/cli/tests/dump-config-schema.expected.e2e.ts @@ -3,8 +3,7 @@ import { existsSync, mkdtempSync, realpathSync } from 'node:fs' import { copyFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises' import { Ajv2020 } from 'ajv/dist/2020.js' -import * as yaml from 'js-yaml' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' import type { ConfigSchemaDump } from '@deepseek-ai/dsh-app-boot' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -162,7 +161,7 @@ describe.skipIf(!builtArtifactsExist)('dsh --dump-config-schema assembled output const composed = await dump(fixture, [], '--dump-config') const validator = new Ajv2020({ strict: false, validateFormats: false }) const validate = validator.compile(document) - expect(validate(yaml.load(composed.stdout, { schema: entryListSchema })), JSON.stringify(validate.errors)).toBe(true) + expect(validate(parseEntryYaml(composed.stdout)), JSON.stringify(validate.errors)).toBe(true) expect(validate([{ name: `${packageName}/namespace`, config: { attempts: 'wrong' } }])).toBe(false) const patch = validator.compile({ $schema: document.$schema, $defs: document.$defs, $ref: '#/$defs/patchList' }) expect(patch([{ id: 'schema-class', config: { enabled: 'wrong' } }])).toBe(false) diff --git a/apps/cli/tests/lazy-search-startup.compat.spec.ts b/apps/cli/tests/lazy-search-startup.compat.spec.ts index dfb92dc340..ed1efb0a16 100644 --- a/apps/cli/tests/lazy-search-startup.compat.spec.ts +++ b/apps/cli/tests/lazy-search-startup.compat.spec.ts @@ -15,7 +15,7 @@ import { mkdtemp, readFile, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' import { fileURLToPath } from 'node:url' -import yaml from 'js-yaml' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' import { describe, expect, it } from 'vitest' const repoRoot = fileURLToPath(new URL('../../../', import.meta.url)) @@ -37,12 +37,6 @@ interface PatchEntry extends ConfigRow { insert?: ConfigRow[] } -const jsExprType = new yaml.Type('tag:yaml.org,2002:js', { - kind: 'scalar', - construct: value => String(value), -}) -const configSchema = yaml.JSON_SCHEMA.extend(jsExprType) - /** Boot the built Web CLI, wait for its settled URL, then dispose through SIGTERM. */ function runBuiltWeb(cwd: string): Promise<{ stdout: string; stderr: string; code: number }> { return new Promise((resolveRun, rejectRun) => { @@ -103,9 +97,9 @@ describe.skipIf(!requireBuiltArtifacts)('built CLI lazy-search startup', () => { it('boots and disposes the shipped composition with full-text search off by default', async () => { expect(existsSync(builtBin), `missing built CLI ${resolve(builtBin)}; run pnpm build`).toBe(true) expect(existsSync(webDist), `missing Web dist ${resolve(webDist)}; run pnpm run build:web`).toBe(true) - const baseRows = (yaml.load(await readFile(baseConfigPath, 'utf8'), { schema: configSchema }) as PatchEntry[]) + const baseRows = (parseEntryYaml(await readFile(baseConfigPath, 'utf8')) as PatchEntry[]) .flatMap(entry => entry.insert ?? [entry]) - const webRows = (yaml.load(await readFile(webConfigPath, 'utf8'), { schema: configSchema }) as PatchEntry[]) + const webRows = (parseEntryYaml(await readFile(webConfigPath, 'utf8')) as PatchEntry[]) .flatMap(entry => entry.insert ?? [entry]) const baseRow = baseRows.find(row => row.id === 'session-query-sqlite') const webRow = webRows.find(row => row.id === 'session-query-sqlite') diff --git a/apps/cli/tests/windows-shell.spec.ts b/apps/cli/tests/windows-shell.spec.ts index c10f7c869a..858080ef42 100644 --- a/apps/cli/tests/windows-shell.spec.ts +++ b/apps/cli/tests/windows-shell.spec.ts @@ -15,8 +15,7 @@ import { mkdtempSync, rmSync, readFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' -import yaml from 'js-yaml' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' import { evaluate } from '@deepseek-ai/cordis-plugin-loader' import { bundlePatchPaths, composeEntries, initProfile, loadProfile, PROFILES_DIR } from '@deepseek-ai/dsh-app-boot' @@ -104,7 +103,7 @@ describe('shipped agent presets gate both shell tools by platform', () => { const webBundle = fileURLToPath(new URL('../../../packages/bundle/web-app/', import.meta.url)) const webManifest = JSON.parse(readFileSync(join(webBundle, 'package.json'), 'utf8')) as { dsh: { bundle: { patch: string[] } } } const presetRows = composeEntries([bundlePatchPaths(webBundle, webManifest.dsh.bundle).flatMap(file => - yaml.load(readFileSync(file, 'utf8'), { schema: entryListSchema }) as import('@deepseek-ai/cordis-plugin-include').PatchOptions[])]) + parseEntryYaml(readFileSync(file, 'utf8')) as import('@deepseek-ai/cordis-plugin-include').PatchOptions[])]) const definitions = presetRows.filter(row => row.name === '@deepseek-ai/dsh-agent-preset').map(row => row.config as import('@deepseek-ai/dsh-agent-preset-registry').PresetDefinition) diff --git a/apps/web/tests/client-ui-stats-panel.e2e.ts b/apps/web/tests/client-ui-stats-panel.e2e.ts index fc0a51b3b5..5ea9061afb 100644 --- a/apps/web/tests/client-ui-stats-panel.e2e.ts +++ b/apps/web/tests/client-ui-stats-panel.e2e.ts @@ -7,8 +7,7 @@ import { readFileSync } from 'node:fs' import type { Browser, Page } from 'playwright' import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' -import * as yaml from 'js-yaml' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' import { createAssistantMessage, createMessage, createUserMessage, ToolCallId, type AssistantStreamRecord, type TokenUsage, @@ -31,7 +30,7 @@ const MODE = webSnapshotMode() /** Overlay layer entries, for the composition guard below. */ function profileEntries(path: string): unknown[] { - const parsed = yaml.load(readFileSync(path, 'utf8'), { schema: entryListSchema }) + const parsed = parseEntryYaml(readFileSync(path, 'utf8')) if (!Array.isArray(parsed)) throw new Error(`profile layer at ${path} must be a list`) return parsed } diff --git a/apps/web/tests/scaffold.ts b/apps/web/tests/scaffold.ts index 2b173325e4..55ae66f480 100644 --- a/apps/web/tests/scaffold.ts +++ b/apps/web/tests/scaffold.ts @@ -33,8 +33,7 @@ import { expect } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { DSH_LAUNCH_ENVIRONMENT_KEY, type LaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' import Loader from '@deepseek-ai/cordis-plugin-loader' -import { entryListSchema, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' -import yaml from 'js-yaml' +import { stringifyEntryYaml, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' import { captureExpectedWorkspaceSnapshot, captureWorkspaceSnapshot, @@ -807,7 +806,7 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise { ? { ...plugin, config: { refreshIntervalMs: 0 } } : plugin) const path = join(dir, 'time-context-every-step.patch.yml') - await writeFile(path, dump([ + await writeFile(path, stringifyEntryYaml([ { id: 'preset-standard', config: { ...config, plugins } }, - ], { schema: entryListSchema, noRefs: true, lineWidth: -1 })) + ], { lineWidth: -1 })) return path } diff --git a/apps/web/tests/settings-import.e2e.ts b/apps/web/tests/settings-import.e2e.ts index 44a14f0ac0..8b26362942 100644 --- a/apps/web/tests/settings-import.e2e.ts +++ b/apps/web/tests/settings-import.e2e.ts @@ -5,8 +5,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { chromium } from 'playwright' import { expect, it } from 'vitest' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' -import yaml from 'js-yaml' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' import { WELCOME_NOTICE_VERSION, launchWebScaffold, watchConsole } from './scaffold.ts' import { ZH_BROWSER_LOCALE } from './support.ts' @@ -24,7 +23,7 @@ it('imports settings.yaml into the profile once and applies the imported values' const patchPath = join(harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml') type Row = { id?: string; config?: Record } const config = (id: string): Record | undefined => - (yaml.load(readFileSync(patchPath, 'utf8'), { schema: entryListSchema }) as Row[]).find(row => row.id === id)?.config + (parseEntryYaml(readFileSync(patchPath, 'utf8')) as Row[]).find(row => row.id === id)?.config await expect.poll(() => config('ui-theme')?.['fontSize'], { timeout: 10_000 }).toBe(16) expect(config('ui-settings')?.['enabled']).toBe(false) expect(config('ui-settings-general')?.['welcomeNoticeVersion']).toBe(WELCOME_NOTICE_VERSION) diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index c93e55bed5..453fadc682 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -28,7 +28,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:708`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:687`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:694`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:55`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | +| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:54`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | | `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes`, `server` | | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - | | `commands/change` | `emit` | [`packages/interaction/commands/src/types.ts:89`](../packages/interaction/commands/src/types.ts) | [`commands`](../packages/interaction/commands) (`events.dispatch`) | `remotes` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 4a3a34876b..081292be53 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -30,7 +30,7 @@ | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:708`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:687`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:694`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:55`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | +| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:54`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | | `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes`, `server` | | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - | | `commands/change` | `emit` | [`packages/interaction/commands/src/types.ts:89`](../packages/interaction/commands/src/types.ts) | [`commands`](../packages/interaction/commands) (`events.dispatch`) | `remotes` | diff --git a/packages/boot/app-boot/package.json b/packages/boot/app-boot/package.json index 6bcc5fa3d2..bebd0e315e 100644 --- a/packages/boot/app-boot/package.json +++ b/packages/boot/app-boot/package.json @@ -37,7 +37,6 @@ "@deepseek-ai/dsh-package-manifest": "workspace:*", "@eslint-community/regexpp": "^4.12.2", "ajv": "^8.20.0", - "js-yaml": "^4.3.2", "node-addon-require-builtin": "^0.1.9", "resolve.exports": "^2.0.3", "semver": "^7.8.5" @@ -59,7 +58,6 @@ "@deepseek-ai/dsh-launch-environment": "workspace:*", "@deepseek-ai/dsh-home-paths": "workspace:*", "@deepseek-ai/dsh-system-prompt": "workspace:*", - "@types/js-yaml": "^4.0.9", "@types/semver": "^7.8.0", "@deepseek-ai/cordis": "workspace:~" } diff --git a/packages/boot/app-boot/src/compatibility-preflight.ts b/packages/boot/app-boot/src/compatibility-preflight.ts index ae10be63e1..c8aeedf2ad 100644 --- a/packages/boot/app-boot/src/compatibility-preflight.ts +++ b/packages/boot/app-boot/src/compatibility-preflight.ts @@ -5,8 +5,7 @@ import { dirname, extname, isAbsolute, join } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' import type { Context } from '@deepseek-ai/cordis' import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader' -import { applyEntryPatches, entryListSchema, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' -import { load } from 'js-yaml' +import { applyEntryPatches, parseEntryYaml, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' import { resolvePluginResource } from './package-meta.ts' import { barePackageName } from './profile-resolution/resolver.ts' import type {} from './profile-resolution/service.ts' @@ -151,7 +150,7 @@ function preflight( includes.add(filename) try { let data: unknown - try { data = load(readFileSync(filename, 'utf8'), { schema: entryListSchema }) } + try { data = parseEntryYaml(readFileSync(filename, 'utf8')) } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || config.initial === undefined) return undefined data = config.initial diff --git a/packages/boot/app-boot/src/config-schema/collect.ts b/packages/boot/app-boot/src/config-schema/collect.ts index 4bd1e7a40b..ab18fc035c 100644 --- a/packages/boot/app-boot/src/config-schema/collect.ts +++ b/packages/boot/app-boot/src/config-schema/collect.ts @@ -3,10 +3,9 @@ import { readFile, realpath } from 'node:fs/promises' import { extname, join } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' -import * as yaml from 'js-yaml' import Loader, { EntryGroup, ModuleLoader, isJsExpr, type EntryOptions } from '@deepseek-ai/cordis-plugin-loader' import Group from '@deepseek-ai/cordis-plugin-group' -import Include, { applyEntryPatches, entryListSchema, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' +import Include, { applyEntryPatches, entryYamlErrorPosition, parseEntryYaml, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' import type { Profile, RuntimeResolution } from '../profile.ts' import { installRuntimeInterception } from '../profile-resolution/resolver.ts' import { buildConfigSchemaDocument } from './document.ts' @@ -148,10 +147,11 @@ export async function collectConfigSchemas( } if (content !== undefined) { try { - source = extension === '.json' ? JSON.parse(content) : yaml.load(content, { schema: entryListSchema }) + source = extension === '.json' ? JSON.parse(content) : parseEntryYaml(content) } catch (error) { // Parser messages can quote configuration values; retain only the file and location. - const at = error instanceof yaml.YAMLException ? ` at line ${error.mark.line + 1}, column ${error.mark.column + 1}` : '' + const position = extension === '.json' ? undefined : entryYamlErrorPosition(error) + const at = position === undefined ? '' : ` at line ${position.line}, column ${position.column}` throw new Error(`invalid ${extension === '.json' ? 'JSON' : 'YAML'} include ${filename}${at}`) } } diff --git a/packages/boot/app-boot/src/index.ts b/packages/boot/app-boot/src/index.ts index daf1406a43..f8f63ff8c5 100644 --- a/packages/boot/app-boot/src/index.ts +++ b/packages/boot/app-boot/src/index.ts @@ -12,10 +12,9 @@ import { inspect, parseEnv } from 'node:util' import { captureStartupComposition, type StartupCompositionDiagnostic } from './startup-diagnostics.ts' export type { StartupCompositionDiagnostic, StartupPluginState, StartupServiceState } from './startup-diagnostics.ts' import { basename, dirname, isAbsolute, resolve } from 'node:path' -import * as yaml from 'js-yaml' import { Context, type Fiber, type FiberState } from '@deepseek-ai/cordis' import Loader, { type Entry, type EntryGroup, type EntryOptions } from '@deepseek-ai/cordis-plugin-loader' -import Include, { applyEntryPatches, entryListSchema, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' +import Include, { applyEntryPatches, parseEntryYaml, stringifyEntryYaml, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' import Group from '@deepseek-ai/cordis-plugin-group' import { dshHomePath, resolveDshHome } from '@deepseek-ai/dsh-home-paths' import { createLaunchEnvironmentSnapshot, type LaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' @@ -258,13 +257,6 @@ export function loadLayeredEnv( const bootstrapIncludes = new WeakMap() -// The include's YAML dialect (`!!js` scalars become expression nodes the -// Loader interpolates against each entry's injection-ready context), imported -// from the include itself so patch parsing and config dumping can never drift -// from what the include mounts. User patch layers share it so they may -// reference `process.env`. -const userPatchesSchema = entryListSchema - /** What a caller of {@link recomposeProfile} already did and requires. */ export interface ProfileRecompositionOptions { /** Explicit enablement targets whose existing failures also reject the recomposition. */ @@ -573,7 +565,7 @@ function parsePatchList( ): PatchOptions[] { let parsed: unknown try { - parsed = yaml.load(content, { schema: userPatchesSchema }) + parsed = parseEntryYaml(content) } catch (error) { throw new Error(`${binName}: failed to parse ${label} ${file}: ${String(error)}`) } @@ -642,7 +634,7 @@ export function renderConfigDump( } let parsed: unknown try { - parsed = yaml.load(content, { schema: entryListSchema }) + parsed = parseEntryYaml(content) } catch (error) { throw new Error(`${binName}: failed to parse config ${absoluteConfigPath}: ${String(error)}`) } @@ -703,7 +695,7 @@ function groupedDump( const flush = (): void => { if (currentLabel === undefined || group.length === 0) return lines.push(`# == ${currentLabel}`) - lines.push(yaml.dump(group, { schema: entryListSchema, noRefs: true }).trimEnd()) + lines.push(stringifyEntryYaml(group).trimEnd()) group = [] } for (let index = 0; index < composed.length; index += 1) { diff --git a/packages/boot/app-boot/tests/compatibility-preflight.spec.ts b/packages/boot/app-boot/tests/compatibility-preflight.spec.ts index e753fa5b4d..0fcf850d56 100644 --- a/packages/boot/app-boot/tests/compatibility-preflight.spec.ts +++ b/packages/boot/app-boot/tests/compatibility-preflight.spec.ts @@ -4,9 +4,8 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { pathToFileURL } from 'node:url' import { Context } from '@deepseek-ai/cordis' -import { entryListSchema, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' +import { parseEntryYaml, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader' -import { load } from 'js-yaml' import { describe, expect, it, onTestFinished, vi } from 'vitest' import { PROFILE_COMPATIBILITY_FILENAME, PluginPackages, boot, getDshRuntimeVersion, @@ -358,7 +357,7 @@ it('reuses the documented literal Include dialect when reading included entries' f.plugin('allowed-plugin') const list = join(f.dir, 'nested.cordis.yml') writeFileSync(list, '- id: nested\n name: allowed-plugin\n') - expect(load(readFileSync(list, 'utf8'), { schema: entryListSchema })).toEqual([{ id: 'nested', name: 'allowed-plugin' }]) + expect(parseEntryYaml(readFileSync(list, 'utf8'))).toEqual([{ id: 'nested', name: 'allowed-plugin' }]) // The launcher mounts an Include with a file URL, which a Windows path cannot stand in for: `C:` reads as a scheme. expect(await f.run([{ insert: [{ id: 'outer', name: 'cordis:include', config: { path: pathToFileURL(list).href } }] }])) .toEqual(['import:allowed-plugin', 'apply:allowed-plugin']) diff --git a/packages/boot/app-boot/tests/config-dump.spec.ts b/packages/boot/app-boot/tests/config-dump.spec.ts index 6703df20e0..8a56d57e34 100644 --- a/packages/boot/app-boot/tests/config-dump.spec.ts +++ b/packages/boot/app-boot/tests/config-dump.spec.ts @@ -12,8 +12,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { pathToFileURL } from 'node:url' import { afterAll, describe, expect, it, vi } from 'vitest' -import * as yaml from 'js-yaml' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' import { loadOverlayPatches, renderConfigDump } from '../src/index.ts' const NAME = 'dsh-test-bin' @@ -73,7 +72,7 @@ describe('renderConfigDump', () => { ], () => {}) // Comments do not break loadability: the dump parses as one document // equal to what boot() would mount. - const parsed = yaml.load(dump, { schema: entryListSchema }) as { + const parsed = parseEntryYaml(dump) as { id: string config?: Record }[] @@ -140,7 +139,7 @@ describe('renderConfigDump', () => { { label: 'b.yml', patches: [{ id: 'child', config: { v: 2 } }] }, ], line => void warnings.push(line)) expect(warnings).toEqual([`${NAME}: [b.yml] patch: entry "child" not found`]) - const parsed = yaml.load(dump, { schema: entryListSchema }) as { + const parsed = parseEntryYaml(dump) as { config?: { config?: { v?: number } }[] }[] expect(parsed[0]?.config?.[0]?.config?.v).toBe(1) @@ -169,7 +168,7 @@ describe('renderConfigDump', () => { line => void warnings.push(line), ) expect(warnings).toEqual([`${NAME}: [overlay.yml] patch: entry "only-on-another-surface" not found`]) - const parsed = yaml.load(dump, { schema: entryListSchema }) as { config?: { value?: string } }[] + const parsed = parseEntryYaml(dump) as { config?: { value?: string } }[] expect(parsed[0]?.config?.value).toBe('patched') }) diff --git a/packages/boot/config-editor/package.json b/packages/boot/config-editor/package.json index 783ce890db..be5241adb0 100644 --- a/packages/boot/config-editor/package.json +++ b/packages/boot/config-editor/package.json @@ -37,15 +37,13 @@ }, "dependencies": { "@deepseek-ai/dsh-atomic-write": "workspace:*", - "yaml": "^2.8.1", - "js-yaml": "^4.3.2" + "yaml": "^2.8.1" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/cordis-plugin-loader": "workspace:~", "@deepseek-ai/dsh-hmr": "workspace:*", "@deepseek-ai/cordis-plugin-include": "workspace:~", - "@types/js-yaml": "^4.0.9", "@deepseek-ai/dsh-app-boot": "workspace:*" }, "peerDependenciesMeta": { diff --git a/packages/boot/config-editor/src/index.ts b/packages/boot/config-editor/src/index.ts index 8fe686e478..a13541199c 100644 --- a/packages/boot/config-editor/src/index.ts +++ b/packages/boot/config-editor/src/index.ts @@ -3,8 +3,7 @@ import { readFile } from 'node:fs/promises' import { join } from 'node:path' import { isDeepStrictEqual } from 'node:util' import { Context, FiberState, Service } from '@deepseek-ai/cordis' -import { entryListSchema, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' -import yaml from 'js-yaml' +import { parseEntryYaml, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' import type { Entry, EntryOptions } from '@deepseek-ai/cordis-plugin-loader' import type {} from '@deepseek-ai/dsh-hmr' import { composeEntries, loadProfileDirectory, readProfilePatches, reconcileProfilePatches } from '@deepseek-ai/dsh-app-boot' @@ -133,7 +132,7 @@ export class ConfigEditor extends Service { } }) const profile = this.ownerContext.profileContext const loaded = loadProfileDirectory('dsh', profile.dir, profile.installAnchor) - const patches = readProfilePatches('dsh', profile, { ...loaded, patches: yaml.load(String(document), { schema: entryListSchema }) as PatchOptions[] }) + const patches = readProfilePatches('dsh', profile, { ...loaded, patches: parseEntryYaml(String(document)) as PatchOptions[] }) const effective = flatten(composeEntries([patches])).find(row => row.id === entry.options.id) if (!isDeepStrictEqual(effective?.config ?? {}, next)) { throw new Error(`Configuration for "${entry.options.id}" is overridden by a home patch or command-line overlay`) diff --git a/packages/bundle/acp-app/tests/acp-app.spec.ts b/packages/bundle/acp-app/tests/acp-app.spec.ts index 925c4e8044..2c176bd770 100644 --- a/packages/bundle/acp-app/tests/acp-app.spec.ts +++ b/packages/bundle/acp-app/tests/acp-app.spec.ts @@ -3,9 +3,8 @@ import { readFileSync } from 'node:fs' import { resolve } from 'node:path' import { fileURLToPath } from 'node:url' -import * as yaml from 'js-yaml' import { describe, expect, it } from 'vitest' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' describe('dsh-acp-app bundle', () => { it('declares startup-gated ACP serving without overriding base HMR policy', () => { @@ -16,10 +15,7 @@ describe('dsh-acp-app bundle', () => { } expect(manifest.dsh?.bundle?.patch).toBe('./cordis.patch.yml') expect(manifest.dependencies).toHaveProperty('@deepseek-ai/dsh-acp') - const patches = yaml.load( - readFileSync(resolve(root, manifest.dsh!.bundle!.patch!), 'utf8'), - { schema: entryListSchema }, - ) as Array<{ + const patches = parseEntryYaml(readFileSync(resolve(root, manifest.dsh!.bundle!.patch!), 'utf8')) as Array<{ id?: string disabled?: boolean insert?: Array<{ config?: { model?: string; provider?: string }; id?: string; inject?: string[]; name?: string }> diff --git a/packages/bundle/base/tests/base.spec.ts b/packages/bundle/base/tests/base.spec.ts index 4a9d5b5c54..fdd22df18c 100644 --- a/packages/bundle/base/tests/base.spec.ts +++ b/packages/bundle/base/tests/base.spec.ts @@ -7,8 +7,7 @@ import { existsSync, readFileSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { resolve } from 'node:path' import { describe, expect, it } from 'vitest' -import * as yaml from 'js-yaml' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' import { evaluate } from '@deepseek-ai/cordis-plugin-loader' describe('dsh-base bundle', () => { @@ -21,10 +20,7 @@ describe('dsh-base bundle', () => { dsh?: { bundle?: { patch?: string } } } expect(manifest.dsh?.bundle?.patch).toBe('./cordis.patch.yml') - const parsed = yaml.load( - readFileSync(resolve(root, manifest.dsh!.bundle!.patch!), 'utf8'), - { schema: entryListSchema }, - ) + const parsed = parseEntryYaml(readFileSync(resolve(root, manifest.dsh!.bundle!.patch!), 'utf8')) expect(Array.isArray(parsed)).toBe(true) // The base layer is one insert list over the empty profile root. const rows = (parsed as { insert?: { id?: string; config?: Record; disabled?: boolean }[] }[]).flatMap( @@ -57,10 +53,7 @@ describe('dsh-base bundle', () => { it('gates each shell stack by platform with a symmetric disabled expression', () => { const root = fileURLToPath(new URL('..', import.meta.url)) - const parsed = yaml.load( - readFileSync(resolve(root, 'cordis.patch.yml'), 'utf8'), - { schema: entryListSchema }, - ) + const parsed = parseEntryYaml(readFileSync(resolve(root, 'cordis.patch.yml'), 'utf8')) if (!Array.isArray(parsed)) throw new TypeError('base patch must parse to a patch list') const rows = parsed.flatMap((patch): Record[] => typeof patch === 'object' && patch !== null diff --git a/packages/bundle/sdk-app/tests/sdk-app.spec.ts b/packages/bundle/sdk-app/tests/sdk-app.spec.ts index 6ab9bd10ff..286f6f0cbf 100644 --- a/packages/bundle/sdk-app/tests/sdk-app.spec.ts +++ b/packages/bundle/sdk-app/tests/sdk-app.spec.ts @@ -3,9 +3,8 @@ import { readFileSync } from 'node:fs' import { resolve } from 'node:path' import { fileURLToPath } from 'node:url' -import * as yaml from 'js-yaml' import { describe, expect, it } from 'vitest' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' describe('dsh-sdk-app bundle', () => { it('enables plugin management while keeping JSON-RPC dependencies stable until restart', () => { @@ -16,10 +15,7 @@ describe('dsh-sdk-app bundle', () => { } expect(manifest.dsh?.bundle?.patch).toBe('./cordis.patch.yml') expect(manifest.dependencies).toHaveProperty('@deepseek-ai/dsh-sdk-jsonrpc-server') - const patches = yaml.load( - readFileSync(resolve(root, manifest.dsh!.bundle!.patch!), 'utf8'), - { schema: entryListSchema }, - ) as Array<{ id?: string; disabled?: boolean; insert?: Array<{ id?: string; inject?: string[]; name?: string }> }> + const patches = parseEntryYaml(readFileSync(resolve(root, manifest.dsh!.bundle!.patch!), 'utf8')) as Array<{ id?: string; disabled?: boolean; insert?: Array<{ id?: string; inject?: string[]; name?: string }> }> expect(patches.find(patch => patch.id === 'hmr')).toMatchObject({ disabled: true }) expect(patches.find(patch => patch.id === 'tool-plugin-manager')).toMatchObject({ disabled: false }) expect(patches.find(patch => patch.id === 'session-title-llm')).toMatchObject({ disabled: true }) diff --git a/packages/bundle/sdk-minimal/tests/sdk-minimal.spec.ts b/packages/bundle/sdk-minimal/tests/sdk-minimal.spec.ts index 2a96ffc076..3357798d2e 100644 --- a/packages/bundle/sdk-minimal/tests/sdk-minimal.spec.ts +++ b/packages/bundle/sdk-minimal/tests/sdk-minimal.spec.ts @@ -3,9 +3,8 @@ import { readFileSync } from 'node:fs' import { resolve } from 'node:path' import { fileURLToPath } from 'node:url' -import * as yaml from 'js-yaml' import { describe, expect, it } from 'vitest' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' function packageName(specifier: string): string { return specifier.startsWith('@') ? specifier.split('/').slice(0, 2).join('/') : specifier.split('/')[0]! @@ -19,10 +18,7 @@ describe('dsh-sdk-minimal bundle', () => { dsh?: { bundle?: { patch?: string } } } expect(manifest.dsh?.bundle?.patch).toBe('./cordis.patch.yml') - const patches = yaml.load( - readFileSync(resolve(root, manifest.dsh!.bundle!.patch!), 'utf8'), - { schema: entryListSchema }, - ) as Array<{ insert?: Array<{ id?: string; inject?: string[]; name?: string; config?: Record; disabled?: unknown }> }> + const patches = parseEntryYaml(readFileSync(resolve(root, manifest.dsh!.bundle!.patch!), 'utf8')) as Array<{ insert?: Array<{ id?: string; inject?: string[]; name?: string; config?: Record; disabled?: unknown }> }> expect(patches).toHaveLength(1) const rows = patches[0]?.insert ?? [] expect(rows.map(row => [row.id, row.name])).toEqual([ diff --git a/packages/experimental/cua-bundle/package.json b/packages/experimental/cua-bundle/package.json index 93612c3ffc..cc7f8216f3 100644 --- a/packages/experimental/cua-bundle/package.json +++ b/packages/experimental/cua-bundle/package.json @@ -51,7 +51,6 @@ "devDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/cordis-plugin-include": "workspace:~", - "js-yaml": "^4.2.0", "@deepseek-ai/cordis-plugin-loader": "workspace:~" }, "optionalDependencies": { diff --git a/packages/experimental/cua-bundle/tests/platform.spec.ts b/packages/experimental/cua-bundle/tests/platform.spec.ts index 4230e4f406..6d10bc2252 100644 --- a/packages/experimental/cua-bundle/tests/platform.spec.ts +++ b/packages/experimental/cua-bundle/tests/platform.spec.ts @@ -2,14 +2,11 @@ import { readFile } from 'node:fs/promises' import { Context } from '@deepseek-ai/cordis' import Loader, { interpolate, type EntryOptions } from '@deepseek-ai/cordis-plugin-loader' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' -import { load } from 'js-yaml' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' import { expect, it, vi } from 'vitest' it.each(['darwin', 'win32', 'linux'])('loads the exported patch directly on %s and imports the native provider only on Darwin', async (platform) => { - const patch = load(await readFile(new URL('../cordis.patch.yml', import.meta.url), 'utf8'), { - schema: entryListSchema, - }) as { insert: EntryOptions[] }[] + const patch = parseEntryYaml(await readFile(new URL('../cordis.patch.yml', import.meta.url), 'utf8')) as { insert: EntryOptions[] }[] const ctx = new Context() await ctx.plugin(Loader) if (!ctx.loader.internal) throw new Error('Loader module importer is unavailable') diff --git a/packages/experimental/inspector-profile/package.json b/packages/experimental/inspector-profile/package.json index f5f40445dd..23df26e9c9 100644 --- a/packages/experimental/inspector-profile/package.json +++ b/packages/experimental/inspector-profile/package.json @@ -48,7 +48,6 @@ }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/cordis-plugin-include": "workspace:~", - "js-yaml": "^4.3.2" + "@deepseek-ai/cordis-plugin-include": "workspace:~" } } diff --git a/packages/experimental/inspector-profile/tests/profile.spec.ts b/packages/experimental/inspector-profile/tests/profile.spec.ts index 7fcfa5813b..4992f2fb1c 100644 --- a/packages/experimental/inspector-profile/tests/profile.spec.ts +++ b/packages/experimental/inspector-profile/tests/profile.spec.ts @@ -2,8 +2,7 @@ import { readFileSync } from 'node:fs' import { describe, expect, it } from 'vitest' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' -import * as yaml from 'js-yaml' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' describe('Inspector profile bundle', () => { it('publishes one layer containing both inspectors and the Statistics view', () => { @@ -19,9 +18,7 @@ describe('Inspector profile bundle', () => { '@deepseek-ai/dsh-experimental-inspector': 'workspace:*', '@deepseek-ai/dsh-experimental-session-inspector': 'workspace:*', }) - expect(yaml.load(readFileSync(new URL(`../${manifest.dsh.bundle.patch}`, import.meta.url), 'utf8'), { - schema: entryListSchema, - })).toEqual([{ insert: [ + expect(parseEntryYaml(readFileSync(new URL(`../${manifest.dsh.bundle.patch}`, import.meta.url), 'utf8'))).toEqual([{ insert: [ { id: 'experimental-inspector', name: '@deepseek-ai/dsh-experimental-inspector', disabled: false, config: { captureFetch: true }, diff --git a/packages/experimental/personalized-recommendations/package.json b/packages/experimental/personalized-recommendations/package.json index b94017f26f..00be87ebfa 100644 --- a/packages/experimental/personalized-recommendations/package.json +++ b/packages/experimental/personalized-recommendations/package.json @@ -47,7 +47,6 @@ "devDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/cordis-plugin-include": "workspace:~", - "js-yaml": "^4.3.2", "@deepseek-ai/cordis-plugin-timer": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-api-remote-access": "workspace:*", diff --git a/packages/experimental/personalized-recommendations/tests/bundle.spec.ts b/packages/experimental/personalized-recommendations/tests/bundle.spec.ts index 7856031d47..e3e9d5d588 100644 --- a/packages/experimental/personalized-recommendations/tests/bundle.spec.ts +++ b/packages/experimental/personalized-recommendations/tests/bundle.spec.ts @@ -4,9 +4,8 @@ import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, it, onTestFinished } from 'vitest' -import * as yaml from 'js-yaml' import type { Context } from '@deepseek-ai/cordis' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' import Timer from '@deepseek-ai/cordis-plugin-timer' import { boot, initProfile, loadProfileDirectory, readProfilePatches, type ProfileContext } from '@deepseek-ai/dsh-app-boot' import Hmr from '@deepseek-ai/dsh-hmr' @@ -32,9 +31,7 @@ const manifest = JSON.parse(readFileSync(new URL('../package.json', import.meta. dependencies: Record dsh: { bundle: { patch: string } } } -const patch = yaml.load(readFileSync(new URL(`../${manifest.dsh.bundle.patch}`, import.meta.url), 'utf8'), { - schema: entryListSchema, -}) as { insert: Row[] }[] +const patch = parseEntryYaml(readFileSync(new URL(`../${manifest.dsh.bundle.patch}`, import.meta.url), 'utf8')) as { insert: Row[] }[] const rows = patch[0]?.insert ?? [] /** A browser row's Host entry is an empty `apply`; its contribution loads in the Client. */ @@ -133,7 +130,7 @@ it('addresses every row through its own id and switches the shared card service await toggle('action-cards', false) expect(ctx.get('actionCards')).toBeUndefined() expect(await skills()).toEqual([]) - expect(yaml.load(await readFile(profile.patchPath, 'utf8'))).toEqual([ + expect(parseEntryYaml(await readFile(profile.patchPath, 'utf8'))).toEqual([ { id: 'creation-recommendations', disabled: true }, { id: 'action-cards', disabled: true }, ]) await toggle('action-cards', true) @@ -144,5 +141,5 @@ it('addresses every row through its own id and switches the shared card service expect(await skills()).toEqual(['personalized-pages']) await toggle('plugin-recommendations', true) expect(await skills()).toEqual(['official-plugins', 'personalized-pages']) - expect(yaml.load(await readFile(profile.patchPath, 'utf8'))).toEqual([]) + expect(parseEntryYaml(await readFile(profile.patchPath, 'utf8'))).toEqual([]) }, 30_000) diff --git a/packages/experimental/webworker-packer/package.json b/packages/experimental/webworker-packer/package.json index a9b39b76d0..9f261c2dbb 100644 --- a/packages/experimental/webworker-packer/package.json +++ b/packages/experimental/webworker-packer/package.json @@ -40,12 +40,10 @@ "@deepseek-ai/dsh-session-format": "workspace:*", "@deepseek-ai/dsh-session-format-catalog": "workspace:*", "@deepseek-ai/dsh-session-format-v3-to-v4": "workspace:*", - "js-yaml": "^4.3.2", "picomatch": "^4.0.7" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", - "@types/js-yaml": "^4.0.9", "@types/picomatch": "^4.0.3" }, "peerDependencies": { diff --git a/packages/experimental/webworker-packer/src/pack.ts b/packages/experimental/webworker-packer/src/pack.ts index fd394d2d51..0b8ea127cf 100644 --- a/packages/experimental/webworker-packer/src/pack.ts +++ b/packages/experimental/webworker-packer/src/pack.ts @@ -28,8 +28,7 @@ import { type ImageLazyArchive, type ImageManifest, } from '@deepseek-ai/dsh-experimental-webworker-runtime' import picomatch from 'picomatch' -import yaml from 'js-yaml' -import { entryListSchema, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' +import { parseEntryYaml, stringifyEntryYaml, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' import { PROFILE_PATCH_FILENAME } from '@deepseek-ai/dsh-app-boot' import { WRAPPER_CONTRACT, type ImageFiles, type TransformOutcome } from './transform-image.ts' import { EXCLUDE, EXCLUDE_WORKSPACE, IMAGE_ENTRY_SEEDS, PAGE_ASSETS } from './rules.ts' @@ -207,7 +206,7 @@ function treeRosterOf(root: string): string[] { continue } if (!entry.name.endsWith('.yml') && !entry.name.endsWith('.yaml')) continue - collectModuleNames(yaml.load(readFileSync(absolute, 'utf8'), { schema: entryListSchema }), names) + collectModuleNames(parseEntryYaml(readFileSync(absolute, 'utf8')), names) } } walk(root) @@ -696,7 +695,7 @@ export function packVfsImage(options: PackOptions): PackResult { files[`node_modules/${installation.name}/package.json`] = readFileSync(installation.manifest) } if (options.homePatch !== undefined && options.homePatch.length > 0) { - files[HOME_PATCH_PATH] = encoder.encode(yaml.dump(options.homePatch, { schema: entryListSchema, noRefs: true })) + files[HOME_PATCH_PATH] = encoder.encode(stringifyEntryYaml(options.homePatch)) } for (const tree of configTrees) collectTree(tree.directory, files, tree.mount, relativePath => !excluded(relativePath)) diff --git a/packages/experimental/webworker-packer/tests/profile-image.spec.ts b/packages/experimental/webworker-packer/tests/profile-image.spec.ts index 6249b8a2c1..48c7be1d92 100644 --- a/packages/experimental/webworker-packer/tests/profile-image.spec.ts +++ b/packages/experimental/webworker-packer/tests/profile-image.spec.ts @@ -10,8 +10,7 @@ import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { describe, expect, it, type TestContext } from 'vitest' import { OPTIONAL_BUNDLES, PROFILE_TEMPLATES } from '@deepseek-ai/dsh-official-bundles' -import yaml from 'js-yaml' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' import { HOME_PATCH_PATH, MANIFEST_PATH, packVfsImage } from '../src/pack.ts' import { installationManifest, platformHomePatch, profileRoster } from '../src/repository.ts' @@ -93,7 +92,7 @@ describe('image layout', () => { expect(HOME_PATCH_PATH).toBe('home/cordis.patch.yml') const text = new TextDecoder().decode(result.files[HOME_PATCH_PATH]) expect(text).toContain("!!js dshHomePath('sessions')") - expect(yaml.load(text, { schema: entryListSchema })).toEqual(homePatch) + expect(parseEntryYaml(text)).toEqual(homePatch) }) it('refuses an installation that is also a roster package', (test) => { diff --git a/packages/preset/agent-preset-registry/package.json b/packages/preset/agent-preset-registry/package.json index 242639fdba..ad692b8a7e 100644 --- a/packages/preset/agent-preset-registry/package.json +++ b/packages/preset/agent-preset-registry/package.json @@ -65,8 +65,7 @@ "dependencies": { "@deepseek-ai/dsh-app-boot": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", - "zod": "4.4.3", - "js-yaml": "^4.3.2" + "zod": "4.4.3" }, "devDependencies": { "@deepseek-ai/cordis-plugin-group": "workspace:~", @@ -94,7 +93,6 @@ "@deepseek-ai/dsh-sandbox-policy": "workspace:*", "@deepseek-ai/dsh-user-approval": "workspace:*", "@deepseek-ai/dsh-agent-preset": "workspace:*", - "@deepseek-ai/dsh-working-directory": "workspace:*", - "@types/js-yaml": "^4.0.9" + "@deepseek-ai/dsh-working-directory": "workspace:*" } } diff --git a/packages/preset/agent-preset-registry/src/index.ts b/packages/preset/agent-preset-registry/src/index.ts index 5205a58228..0bee8749e1 100644 --- a/packages/preset/agent-preset-registry/src/index.ts +++ b/packages/preset/agent-preset-registry/src/index.ts @@ -4,8 +4,7 @@ import { Context, Service } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' import { bindScopeParent, createScope, scopeOf, scopeParentOf, type Scope, type ScopeKey, type ScopeParentBinding } from '@deepseek-ai/dsh-scope' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' -import { dump } from 'js-yaml' +import { stringifyEntryYaml } from '@deepseek-ai/cordis-plugin-include' import type { Agent } from '@deepseek-ai/dsh-agent' import type { Session } from '@deepseek-ai/dsh-session' // Type-only: the optional `settings` service this registry keeps off the generated pages. @@ -239,7 +238,7 @@ export class AgentPresetRegistry extends TypertRemoteService { } const { id, name, description, plugins } = record.config // The Loader's own dialect, so `!!js` conditions read as declared rather than as expression objects. - const content = dump(plugins, { schema: entryListSchema, noRefs: true, lineWidth: -1 }) + const content = stringifyEntryYaml(plugins, { lineWidth: -1 }) return Promise.resolve({ agentPreset: id, content, ...(name === undefined ? {} : { name }), ...(description === undefined ? {} : { description }), }) diff --git a/packages/preset/agent-preset/package.json b/packages/preset/agent-preset/package.json index b64d6a23d8..5ccc9622f8 100644 --- a/packages/preset/agent-preset/package.json +++ b/packages/preset/agent-preset/package.json @@ -45,8 +45,6 @@ "@deepseek-ai/dsh-compaction-tool-result-pruner": "workspace:*", "@deepseek-ai/dsh-skill": "workspace:*", "@deepseek-ai/dsh-skill-filesystem": "workspace:*", - "@deepseek-ai/schemastery": "workspace:~", - "@types/js-yaml": "^4.0.9", - "js-yaml": "^4.3.2" + "@deepseek-ai/schemastery": "workspace:~" } } diff --git a/packages/preset/agent-preset/tests/skills.spec.ts b/packages/preset/agent-preset/tests/skills.spec.ts index 23ff399c2a..602f2bc57b 100644 --- a/packages/preset/agent-preset/tests/skills.spec.ts +++ b/packages/preset/agent-preset/tests/skills.spec.ts @@ -7,8 +7,7 @@ import { lstatSync, readdirSync, readFileSync, readlinkSync, realpathSync, statS import { dirname, join, matchesGlob, resolve } from 'node:path' import { Context } from '@deepseek-ai/cordis' import { fileURLToPath } from 'node:url' -import * as yaml from 'js-yaml' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' import { codePointLength } from '@deepseek-ai/dsh-compaction-tool-result-pruner' import SkillRegistry, { renderSkillContent } from '@deepseek-ai/dsh-skill' import * as SkillFileSystem from '@deepseek-ai/dsh-skill-filesystem' @@ -94,7 +93,7 @@ describe('the shipped creator skills', () => { for (const name of readdirSync(templates)) { const dir = join(templates, name) const manifest = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as { dsh: { bundle: { patch: string } } } - const patch = yaml.load(readFileSync(join(dir, manifest.dsh.bundle.patch), 'utf8'), { schema: entryListSchema }) + const patch = parseEntryYaml(readFileSync(join(dir, manifest.dsh.bundle.patch), 'utf8')) expect(Array.isArray(patch)).toBe(true) for (const file of readdirSync(dir).filter(entry => entry.endsWith('.js'))) { execFileSync(process.execPath, ['--check', join(dir, file)]) diff --git a/packages/settings/settings/tests/profile-composition.ts b/packages/settings/settings/tests/profile-composition.ts index b0ba588749..fceb74a585 100644 --- a/packages/settings/settings/tests/profile-composition.ts +++ b/packages/settings/settings/tests/profile-composition.ts @@ -1,9 +1,8 @@ /** Mount source modules through a real profile, patch file, and reload coordinator. */ import { mkdir, readFile, writeFile } from 'node:fs/promises' import { join } from 'node:path' -import yaml from 'js-yaml' import type { Context } from '@deepseek-ai/cordis' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' +import { parseEntryYaml, stringifyEntryYaml } from '@deepseek-ai/cordis-plugin-include' import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader' import Timer from '@deepseek-ai/cordis-plugin-timer' import { initProfile, mountRootInclude, readProfilePatches, type ProfileContext } from '@deepseek-ai/dsh-app-boot' @@ -19,9 +18,9 @@ export async function profileComposition(ctx: Context, home: string, baseFile: s await mkdir(bundle, { recursive: true }) await writeFile(join(home, 'package.json'), '{"name":"test-installation"}\n') await writeFile(join(bundle, 'package.json'), JSON.stringify({ name: 'test-profile-bundle', version: '1.0.0', dsh: { bundle: { patch: 'cordis.patch.yml' } } })) - const rows = yaml.load(await readFile(baseFile, 'utf8'), { schema: entryListSchema }) as EntryOptions[] + const rows = parseEntryYaml(await readFile(baseFile, 'utf8')) as EntryOptions[] for (const row of rows) row.id ??= row.name.replace('@deepseek-ai/dsh-', '') - await writeFile(join(bundle, 'cordis.patch.yml'), yaml.dump([{ insert: rows }], { schema: entryListSchema })) + await writeFile(join(bundle, 'cordis.patch.yml'), stringifyEntryYaml([{ insert: rows }])) await writeFile(join(dir, 'cordis.yml'), '[]\n') const profile: ProfileContext = { name: 'test', startedBundles: ['test-profile-bundle'], dir, patchPath: join(dir, 'cordis.patch.yml'), diff --git a/packages/test-support/client-runtime/package.json b/packages/test-support/client-runtime/package.json index 6c8b0e9c3a..d64df4c47d 100644 --- a/packages/test-support/client-runtime/package.json +++ b/packages/test-support/client-runtime/package.json @@ -25,7 +25,6 @@ "dependencies": { "@testing-library/dom": "^10.4.1", "@testing-library/react": "^16.3.3", - "js-yaml": "^4.3.2", "vitest": "^4.1.11" }, "peerDependencies": { @@ -86,7 +85,6 @@ "@deepseek-ai/dsh-subagent": "workspace:*", "@deepseek-ai/dsh-typert-protocol": "workspace:*", "@deepseek-ai/dsh-web-app": "workspace:*", - "@types/js-yaml": "^4.0.9", "react": "^18.2.0", "react-dom": "^18.2.0", "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*" diff --git a/packages/test-support/client-runtime/src/assembly/bundle-roster.ts b/packages/test-support/client-runtime/src/assembly/bundle-roster.ts index d268bbc84c..d31ab8c876 100644 --- a/packages/test-support/client-runtime/src/assembly/bundle-roster.ts +++ b/packages/test-support/client-runtime/src/assembly/bundle-roster.ts @@ -1,7 +1,7 @@ /** * The browser roster of a `dsh --profile`, read from its bundle patch files * the way the launcher composes them: each bundle's `dsh.bundle.patch` file list is - * parsed with the include plugin's YAML dialect (`entryListSchema`) and + * parsed with the include plugin's `parseEntryYaml` and * composed by its `applyEntryPatches`; every enabled row whose package * declares `dsh.client.platform === 'web'` becomes a roster row carrying that * declaration's `inject` and `immediately`; rows nested in Loader groups count @@ -18,9 +18,8 @@ import { createRequire } from 'node:module' import { basename, dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' import { evaluate, isJsExpr, type EntryOptions } from '@deepseek-ai/cordis-plugin-loader' -import { applyEntryPatches, entryListSchema, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' +import { applyEntryPatches, parseEntryYaml, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' import { exactPackageSpecifier, parseDshClient } from '@deepseek-ai/dsh-client-modules/client' -import * as yaml from 'js-yaml' import { ClientRoster, type ClientRosterRow } from './roster.ts' /** @@ -96,7 +95,7 @@ function readLayer(bundle: string, anchor: string): BundleLayer { } const patches = files.flatMap((patch) => { const file = join(dirname(manifestPath), patch) - const parsed: unknown = yaml.load(readFileSync(file, 'utf8'), { schema: entryListSchema }) + const parsed: unknown = parseEntryYaml(readFileSync(file, 'utf8')) if (!Array.isArray(parsed)) throw new Error(`client-test-runtime: ${file} must be a top-level list of patches`) return parsed as PatchOptions[] }) diff --git a/packages/test-support/session-snapshot/src/launcher.ts b/packages/test-support/session-snapshot/src/launcher.ts index a99ecac2c0..3524da3347 100644 --- a/packages/test-support/session-snapshot/src/launcher.ts +++ b/packages/test-support/session-snapshot/src/launcher.ts @@ -13,7 +13,6 @@ import { createRequire } from 'node:module' import { basename, dirname, join, resolve } from 'node:path' import { Readable, Writable } from 'node:stream' import { pathToFileURL } from 'node:url' -import * as yaml from 'js-yaml' import { client as createAcpClientApp, methods, @@ -37,7 +36,7 @@ import { type SetSessionConfigOptionResponse, type SessionNotification, } from '@agentclientprotocol/sdk' -import { entryListSchema, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' +import { parseEntryYaml, stringifyEntryYaml, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' import { resolveExampleLaunch } from '@deepseek-ai/dsh-loader-smoke' const EXIT_MARKER_GRACE_MS = 250 @@ -417,7 +416,7 @@ function linkProfilePackage(source: string, cwd: string, profile: string, packag export function materializeProfilePatch( source: string, cwd: string, profile: string, targetDir: string, index: number, ): string { - const parsed = yaml.load(readFileSync(source, 'utf8'), { schema: entryListSchema }) + const parsed = parseEntryYaml(readFileSync(source, 'utf8')) if (!Array.isArray(parsed)) throw new Error(`snapshot profile patch must be a top-level array: ${source}`) const patches = parsed as PatchOptions[] const baseDir = dirname(source) @@ -439,7 +438,7 @@ export function materializeProfilePatch( for (const entry of patch.insert ?? []) visitEntry(entry) } const target = join(targetDir, `${String(index)}-${basename(source)}`) - writeFileSync(target, yaml.dump(patches, { schema: entryListSchema, lineWidth: -1, noRefs: true })) + writeFileSync(target, stringifyEntryYaml(patches, { lineWidth: -1 })) return target } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index dfd3aa64d9..00c3c94fb1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2029,9 +2029,6 @@ importers: ajv: specifier: ^8.20.0 version: 8.20.0 - js-yaml: - specifier: ^4.3.2 - version: 4.3.2 node-addon-require-builtin: specifier: ^0.1.9 version: 0.1.9 @@ -2069,9 +2066,6 @@ importers: '@deepseek-ai/schemastery': specifier: link:../../../vendor/schemastery version: link:../../../vendor/schemastery - '@types/js-yaml': - specifier: ^4.0.9 - version: 4.0.9 '@types/semver': specifier: ^7.8.0 version: 7.8.0 @@ -2096,9 +2090,6 @@ importers: '@deepseek-ai/dsh-atomic-write': specifier: workspace:* version: link:../../util/atomic-write - js-yaml: - specifier: ^4.3.2 - version: 4.3.2 yaml: specifier: ^2.8.1 version: 2.9.0 @@ -2118,9 +2109,6 @@ importers: '@deepseek-ai/dsh-hmr': specifier: workspace:* version: link:../hmr - '@types/js-yaml': - specifier: ^4.0.9 - version: 4.0.9 packages/boot/hmr: dependencies: @@ -9840,9 +9828,6 @@ importers: '@deepseek-ai/cordis-plugin-loader': specifier: workspace:~ version: link:../../../vendor/loader - js-yaml: - specifier: ^4.2.0 - version: 4.3.2 optionalDependencies: '@deepseek-ai/dsh-experimental-cua-macos': specifier: workspace:* @@ -10354,9 +10339,6 @@ importers: '@deepseek-ai/cordis-plugin-include': specifier: workspace:~ version: link:../../../vendor/include - js-yaml: - specifier: ^4.3.2 - version: 4.3.2 packages/experimental/liveshare: dependencies: @@ -10684,9 +10666,6 @@ importers: '@deepseek-ai/dsh-tools': specifier: workspace:* version: link:../../core/tools - js-yaml: - specifier: ^4.3.2 - version: 4.3.2 packages/experimental/plugin-market-bundle: dependencies: @@ -11544,9 +11523,6 @@ importers: '@deepseek-ai/dsh-session-format-v3-to-v4': specifier: workspace:* version: link:../../session/session-format-v3-to-v4 - js-yaml: - specifier: ^4.3.2 - version: 4.3.2 picomatch: specifier: ^4.0.7 version: 4.0.7 @@ -11554,9 +11530,6 @@ importers: '@deepseek-ai/cordis': specifier: workspace:~ version: link:../../../vendor/cordis - '@types/js-yaml': - specifier: ^4.0.9 - version: 4.0.9 '@types/picomatch': specifier: ^4.0.3 version: 4.0.3 @@ -13748,12 +13721,6 @@ importers: '@deepseek-ai/dsh-skill-filesystem': specifier: workspace:* version: link:../../skill/skill-filesystem - '@types/js-yaml': - specifier: ^4.0.9 - version: 4.0.9 - js-yaml: - specifier: ^4.3.2 - version: 4.3.2 packages/preset/agent-preset-registry: dependencies: @@ -13763,9 +13730,6 @@ importers: '@deepseek-ai/schemastery': specifier: link:../../../vendor/schemastery version: link:../../../vendor/schemastery - js-yaml: - specifier: ^4.3.2 - version: 4.3.2 zod: specifier: 4.4.3 version: 4.4.3 @@ -13848,9 +13812,6 @@ importers: '@deepseek-ai/dsh-working-directory': specifier: workspace:* version: link:../../session/working-directory - '@types/js-yaml': - specifier: ^4.0.9 - version: 4.0.9 packages/preset/persona: dependencies: @@ -17088,9 +17049,6 @@ importers: '@testing-library/react': specifier: ^16.3.3 version: 16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) - js-yaml: - specifier: ^4.3.2 - version: 4.3.2 vitest: specifier: ^4.1.11 version: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@22.20.1)(@vitest/coverage-v8@4.1.11)(happy-dom@20.11.6)(jsdom@29.1.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.0)) @@ -17188,9 +17146,6 @@ importers: '@deepseek-ai/dsh-web-app': specifier: workspace:* version: link:../../bundle/web-app - '@types/js-yaml': - specifier: ^4.0.9 - version: 4.0.9 react: specifier: ^18.2.0 version: 18.3.1 diff --git a/scripts/cordis-entry-yaml.spec.ts b/scripts/cordis-entry-yaml.spec.ts new file mode 100644 index 0000000000..75d938e84b --- /dev/null +++ b/scripts/cordis-entry-yaml.spec.ts @@ -0,0 +1,39 @@ +/** Include's YAML dialect exports used by DSH configuration tools. */ +import { entryYamlErrorPosition, parseEntryYaml, stringifyEntryYaml } from '@deepseek-ai/cordis-plugin-include' +import { describe, expect, it } from 'vitest' + +describe('Include YAML dialect', () => { + it('reads and writes !!js scalars as expression nodes', () => { + const source = '- id: a\n name: example\n disabled: !!js process.env.OFF\n' + const parsed = parseEntryYaml(source) + expect(parsed).toEqual([{ id: 'a', name: 'example', disabled: { __jsExpr: 'process.env.OFF' } }]) + expect(stringifyEntryYaml(parsed)).toBe(source) + }) + + it('reads binary integers as numbers and dates as strings', () => { + expect(parseEntryYaml('- 0b101\n- 2001-01-01\n- ~\n')).toEqual([5, '2001-01-01', null]) + expect(parseEntryYaml('')).toBeUndefined() + }) + + it('writes repeated references in full', () => { + const shared = { value: 1 } + expect(stringifyEntryYaml([{ config: shared }, { config: shared }])).toBe('- config:\n value: 1\n- config:\n value: 1\n') + }) + + it('folds long scalars at the requested line width', () => { + const value = [{ text: Array.from({ length: 20 }, (_, index) => `word${String(index)}`).join(' ') }] + expect(stringifyEntryYaml(value).split('\n').length).toBeGreaterThan(2) + expect(stringifyEntryYaml(value, { lineWidth: -1 }).split('\n')).toHaveLength(2) + }) + + it('locates parse errors', () => { + let error: unknown + try { + parseEntryYaml('- id: a\n name: [\n') + } catch (caught) { + error = caught + } + expect(entryYamlErrorPosition(error)).toEqual({ line: 3, column: 1 }) + expect(entryYamlErrorPosition(new Error('other'))).toBeUndefined() + }) +}) diff --git a/scripts/cordis-yaml.ts b/scripts/cordis-yaml.ts index 43f81af22e..2389c7893f 100644 --- a/scripts/cordis-yaml.ts +++ b/scripts/cordis-yaml.ts @@ -3,30 +3,20 @@ * @module scripts/cordis-yaml */ -import * as yaml from 'js-yaml' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' /** A Loader `!!js` expression preserved as data instead of executed. */ export interface JsExpr { __jsExpr: string } -const jsExprType = new yaml.Type('tag:yaml.org,2002:js', { - kind: 'scalar', - resolve: data => typeof data === 'string', - construct: (data: unknown): JsExpr => { - if (typeof data !== 'string') throw new TypeError('!!js requires a scalar string') - return { __jsExpr: data } - }, -}) -const schema = yaml.JSON_SCHEMA.extend(jsExprType) - /** * Parse a Cordis config while preserving Loader `!!js` expressions as data. * @param source - Cordis YAML source text. * @returns the parsed YAML value. */ export function loadCordisYaml(source: string): unknown { - return yaml.load(source, { schema }) + return parseEntryYaml(source) } /** diff --git a/vendor/README.md b/vendor/README.md index c3a4c8e774..bb51a6381d 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -37,7 +37,7 @@ Keep this log exhaustive — every divergence from upstream must be listed. Each - **V7 · JSDoc enrichment**: added `@param`/`@returns` tags and contract documentation (disposal semantics, waterfall veto, bail conditions, error cases) across the public plugin-author surface — `Context` (class, statics, and the `Context` interface properties incl. `root`), module re-exports, shared utility helpers, `EventsService`, `Fiber`, `RegistryService`, `ReflectService`, `Service`, `LoggerService` and their `declare module './context.ts'` overloads. Loader documentation covers `loader/src/{index,internal,config/entry,config/group,config/isolate,config/tree,config/utils}.ts`, including entry ownership, tree mutation methods, and the `!!js` discriminator. The upstream `EventsService.dispatch()` deprecation annotation is omitted: DSH enumerates callbacks to contain each observer failure independently, which the typed dispatch methods do not provide. Timer retains its local class and helper summaries; its README is local documentation because the upstream package has none. Cosmokit and Schemastery add summaries to their exported helpers, types and namespaces, logger-console to its exporters and config namespace, and HMR to its build-failure logger in `hmr/src/error.ts`. Comment-only; no code changes. Motivation: the website API-reference generator renders these docs and hard-errors on undocumented members. Retire this entry when the enrichment is upstreamed. - **V9 · `hmr/src/index.ts` module-watcher readiness and native paths**: realpath the existing watch base, classify framework modules and attach listeners before reporting readiness, and compare config paths using both canonical and configured spellings. This preserves Node module-cache identity across Windows short-name paths and filesystem aliases. The main watcher uses `ignoreInitial: true` so startup reads do not trigger another refresh; exact profile patch watching is owned by `packages/boot/hmr/src/watch-config.ts`. The Include change listener logs a rejected `Include.refresh()` instead of leaving the rejection unhandled; the rejection reports unsaved runtime changes while Include keeps its running tree. Covered by `packages/boot/hmr/tests/watch-config.spec.ts` and `scripts/cordis-vendor-hmr-include.spec.ts`. - **V10 · Vendored Node-compatible TypeScript**: marked erased imports explicitly across `cordis`, `loader`, `include`, `hmr`, and `schemastery` so Node's native TypeScript transform does not request types as runtime exports. Schemastery's source uses an ESM default export and its package declares `type: module`. Conditional exports select `.mjs` for import and `.cjs` for require; without them, concurrent imports under module-hook hosts reach the CJS entry and can race its require of ESM Cosmokit (`ERR_REQUIRE_ESM_RACE_CONDITION`). -- **V11 · Include patch and YAML exports**: `include/src/index.ts` exports upstream `applyPatches` as `applyEntryPatches` and the `!!js` YAML dialect as `entryListSchema`, so `dsh --dump-config` composes entries with the same algorithm that mounting uses. Covered by `packages/boot/app-boot/tests/config-reload.spec.ts` and `scripts/cordis-entry-commit.spec.ts`. +- **V11 · Include patch and YAML exports**: `include/src/index.ts` exports upstream `applyPatches` as `applyEntryPatches`, so `dsh --dump-config` composes entries with the same algorithm that mounting uses. It also exports `parseEntryYaml`, `stringifyEntryYaml` and `entryYamlErrorPosition` over the `!!js` YAML dialect, and `_read()` parses through `parseEntryYaml`, so every DSH reader and writer of Include-dialect YAML uses Include's parser; `stringifyEntryYaml` writes with `noRefs`, while Include's own writer keeps upstream's options. Covered by `packages/boot/app-boot/tests/config-reload.spec.ts`, `scripts/cordis-entry-commit.spec.ts` and `scripts/cordis-entry-yaml.spec.ts`. - **V14 · Include persistence results**: `include/src/index.ts` keeps an error for unsaved journal changes. `flush()` retries pending writes and rejects while changes remain unsaved; `stop()` returns the same result and always stops the child tree; a later successful flush clears previous errors. A failed `refresh()` can also reject while runtime changes remain unsaved. Patch-owned changes route to the parent Include, so callers that need them persisted must flush that parent too. The constructor omits upstream's `ctx.hmr.watch(this.filename, () => this.refresh())` registration because neither HMR provider exposes `watch()`; both find each Include by scanning loader entries for its `filename` and call `refresh()`. Ordinary Fiber teardown keeps its error containment. Covered by `scripts/cordis-include-journal.spec.ts` and `packages/host/directory-picker-auto/tests/loader-composition.spec.ts`. - **V15 · Configuration access across Core, Loader, Include and HMR**: rc.11 Core owns raw `Fiber.config`, `internal/config(fiber, next)`, `internal/commit` and awaited `internal/update(config, next)`. Root-fiber candidate resolution remains available without a plugin schema. Local `rawConfig`, `resolveConfig(candidate)` and `effectiveConfig` accessors retain the DSH consumer API. Fiber caches the object passed to activation or a successful update that keeps the instance; candidate resolution is pure, failed or superseded updates cannot replace the cache, and volatile updates retain references. Loader resolves only entry roots and excludes Group/Include tree carriers, so nested `!!js` expressions wait for their own injections. Include retains its tree-carrier marker and public patch exports, and HMR transfers raw config through the accessors. Covered by `scripts/cordis-config-access.spec.ts`, `scripts/cordis-core-lifecycle.spec.ts` and the boot/HMR suites. - **V16 · `cordis/package.json` publishes `src`**: added `src` to the `files` list, joining the other eight vendored packages. Cordis declares `"./src/*": "./src/*"` in its exports, so a tarball without `src` publishes an export map pointing at absent files; the release change judgement also reads `files` to decide whether a diff reaches the payload, and a package whose only published paths are build output has no tracked path to match. diff --git a/vendor/include/README.md b/vendor/include/README.md index ae01993dc8..1ce78ec9a9 100644 --- a/vendor/include/README.md +++ b/vendor/include/README.md @@ -44,7 +44,7 @@ Patches can insert entries or override fields on entries with a matching `id`. ## Patch composition and persistence -`applyEntryPatches(data, patches, warn)` uses the same upstream algorithm as mounting. It clones file entries even without patches and clones inserted entry lists before indexing them, so later patches can address inserted rows without mutating those input lists. `entryListSchema` exposes Include’s YAML dialect to configuration tools. Nested entry expressions remain literal until their owning Loader entry evaluates them. +`applyEntryPatches(data, patches, warn)` uses the same upstream algorithm as mounting. It clones file entries even without patches and clones inserted entry lists before indexing them, so later patches can address inserted rows without mutating those input lists. `parseEntryYaml(content)` and `stringifyEntryYaml(value, options)` read and write Include’s YAML dialect for configuration tools, and `entryYamlErrorPosition(error)` locates a parse error. `stringifyEntryYaml` writes repeated references in full instead of as aliases. Nested entry expressions remain literal until their owning Loader entry evaluates them. Tree mutations arrive through `commit(change)` and enter a journal. Include merges them with the latest file before writing; file edits win conflicts on the same fields and produce a diagnostic. Patch-owned fields and inserted entries update the parent Include’s patches instead of the included file. Invalid, missing or read-only files leave unsaved changes in memory. diff --git a/vendor/include/src/index.ts b/vendor/include/src/index.ts index 5dd86d50ec..2f905bbe3e 100644 --- a/vendor/include/src/index.ts +++ b/vendor/include/src/index.ts @@ -21,9 +21,45 @@ const JsExpr = new yaml.Type('tag:yaml.org,2002:js', { represent: (data) => data['__jsExpr'], }) -/** YAML dialect preserving child-owned JavaScript expression nodes. */ -export const entryListSchema = yaml.JSON_SCHEMA.extend(JsExpr) -const schema = entryListSchema +const schema = yaml.JSON_SCHEMA.extend(JsExpr) + +/** Options for {@link stringifyEntryYaml}. */ +export interface EntryYamlStringifyOptions { + /** Column at which long scalars are folded; `-1` disables folding. Defaults to 80. */ + lineWidth?: number +} + +/** + * Parse text in Include's YAML dialect. A `!!js` scalar becomes a child-owned JavaScript expression node that stays + * literal until its owning Loader entry evaluates it. + * @param content - YAML source text. + * @returns the parsed value, or `undefined` for an empty document. + * @throws the parser's syntax error; {@link entryYamlErrorPosition} reads its location. + */ +export function parseEntryYaml(content: string): unknown { + return yaml.load(content, { schema }) +} + +/** + * Serialize a value in Include's YAML dialect. JavaScript expression nodes are written as `!!js` scalars, and + * repeated object references are written out in full instead of as aliases. + * @param value - entry list, patch list, or entry fragment to serialize. + * @param options - output formatting. + * @returns YAML text ending with a newline. + */ +export function stringifyEntryYaml(value: unknown, options: EntryYamlStringifyOptions = {}): string { + return yaml.dump(value, { schema, noRefs: true, lineWidth: options.lineWidth ?? 80 }) +} + +/** + * Locate a syntax error thrown by {@link parseEntryYaml}. + * @param error - value thrown by {@link parseEntryYaml}. + * @returns the one-based line and column of the error, or `undefined` when the error carries no source location. + */ +export function entryYamlErrorPosition(error: unknown): { line: number; column: number } | undefined { + if (!(error instanceof yaml.YAMLException) || !error.mark) return undefined + return { line: error.mark.line + 1, column: error.mark.column + 1 } +} const types: Record = { '.json': 'application/json', @@ -255,7 +291,7 @@ export class Include extends EntryTree { let data: any try { data = this.type === 'application/yaml' - ? yaml.load(content, { schema }) + ? parseEntryYaml(content) : JSON.parse(content) } catch (error) { throw new ConfigFileError('parse', this.filename, error) From 968223aaa2343382bad9b3afe91b53027d9a8ef9 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Thu, 5 Nov 2026 17:15:29 +0800 Subject: [PATCH 005/450] feat(web): add the floating Session panel Add dsh-client-ui-session-panel: a Session header toggle and a floating panel seated in the main Conversation body. Plugins register sections (id, order, label) and title controls; the built-in Environment section shows the project directory and accepts rows from other plugins. The panel docks only while the transcript's end gutter can hold it; the Conversation width controls report that gutter through ctx.uiConversation.layouts. A narrower gutter hides it, and the toggle then opens a transient overlay. The turn rail moves to the start edge. --- .../2026-11-05-session-panel.i18n.yaml | 28 ++ .../feature/2026-11-05-session-panel.md | 47 +++ .../feature/2026-11-05-session-panel.zh.md | 47 +++ docs/config-catalog.md | 1 + docs/config-catalog.zh.md | 1 + docs/module-graph.md | 2 + docs/module-graph.zh.md | 2 + docs/subsystems/slots.i18n.yaml | 4 +- docs/subsystems/slots.md | 11 +- docs/subsystems/slots.zh.md | 11 +- packages/bundle/web-app/cordis.patch.yml | 5 + packages/bundle/web-app/package.json | 1 + packages/client/README.i18n.yaml | 4 +- packages/client/README.md | 1 + packages/client/README.zh.md | 1 + packages/client/ui-chat/README.i18n.yaml | 4 +- packages/client/ui-chat/README.md | 2 +- packages/client/ui-chat/README.zh.md | 2 +- .../src/client/chat/TurnNavigator.module.css | 15 +- .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 2 + packages/client/ui-conversation/README.zh.md | 2 + .../ui-conversation/src/client/apply.ts | 11 +- .../src/client/contract/slots.ts | 37 +++ .../src/client/conversation/assembly.ts | 3 + .../src/client/conversation/layouts.ts | 72 ++++ .../ui-conversation/src/client/index.ts | 4 +- .../client/skeleton/ConversationContent.tsx | 25 +- .../skeleton/ConversationWidthControls.tsx | 25 +- .../tests/skeleton.client.spec.tsx | 62 +++- .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 1 + packages/client/ui-primitives/README.zh.md | 1 + .../ui-primitives/src/PanelRow.module.css | 78 +++++ .../client/ui-primitives/src/PanelRow.tsx | 40 +++ packages/client/ui-primitives/src/index.ts | 2 + .../tests/panel-row.client.spec.tsx | 41 +++ .../client/ui-session-panel/README.i18n.yaml | 43 +++ packages/client/ui-session-panel/README.md | 109 ++++++ packages/client/ui-session-panel/README.zh.md | 109 ++++++ .../client/ui-session-panel/locale/de.json | 6 + .../client/ui-session-panel/locale/en.json | 6 + .../client/ui-session-panel/locale/es.json | 6 + .../client/ui-session-panel/locale/fr.json | 6 + .../client/ui-session-panel/locale/ja.json | 6 + .../client/ui-session-panel/locale/pt.json | 6 + .../client/ui-session-panel/locale/ru.json | 6 + .../client/ui-session-panel/locale/zh.json | 6 + packages/client/ui-session-panel/package.json | 78 +++++ .../src/client/EnvironmentSection.tsx | 13 + .../src/client/ProjectRow.module.css | 12 + .../src/client/ProjectRow.tsx | 38 +++ .../src/client/SessionPanel.module.css | 93 ++++++ .../src/client/SessionPanel.tsx | 93 ++++++ .../src/client/SessionPanelToggle.module.css | 39 +++ .../src/client/SessionPanelToggle.tsx | 39 +++ .../src/client/element-ids.ts | 20 ++ .../ui-session-panel/src/client/index.ts | 99 ++++++ .../ui-session-panel/src/client/locales.ts | 79 +++++ .../ui-session-panel/src/client/sections.ts | 66 ++++ .../ui-session-panel/src/client/slots.ts | 132 ++++++++ .../ui-session-panel/src/client/visibility.ts | 89 +++++ .../ui-session-panel/src/css-modules.d.ts | 4 + packages/client/ui-session-panel/src/index.ts | 9 + .../tests/browser-plugin.client.spec.ts | 144 ++++++++ .../tests/components.client.spec.tsx | 272 +++++++++++++++ .../tests/sections.client.spec.ts | 43 +++ .../tests/visibility.client.spec.ts | 89 +++++ .../client/ui-session-panel/tsconfig.json | 57 ++++ .../client/ui-session-panel/tsdown.config.ts | 3 + .../src/client/slot-catalog.ts | 310 ++++++++++++++++-- .../references/packages.md | 1 + pnpm-lock.yaml | 66 ++++ .../verify-package-readme-model-experience.ts | 1 + tsconfig.base.json | 2 + tsconfig.client.json | 1 + 76 files changed, 2743 insertions(+), 61 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-11-05-session-panel.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-11-05-session-panel.md create mode 100644 .agents/notes/implemented/feature/2026-11-05-session-panel.zh.md create mode 100644 packages/client/ui-conversation/src/client/conversation/layouts.ts create mode 100644 packages/client/ui-primitives/src/PanelRow.module.css create mode 100644 packages/client/ui-primitives/src/PanelRow.tsx create mode 100644 packages/client/ui-primitives/tests/panel-row.client.spec.tsx create mode 100644 packages/client/ui-session-panel/README.i18n.yaml create mode 100644 packages/client/ui-session-panel/README.md create mode 100644 packages/client/ui-session-panel/README.zh.md create mode 100644 packages/client/ui-session-panel/locale/de.json create mode 100644 packages/client/ui-session-panel/locale/en.json create mode 100644 packages/client/ui-session-panel/locale/es.json create mode 100644 packages/client/ui-session-panel/locale/fr.json create mode 100644 packages/client/ui-session-panel/locale/ja.json create mode 100644 packages/client/ui-session-panel/locale/pt.json create mode 100644 packages/client/ui-session-panel/locale/ru.json create mode 100644 packages/client/ui-session-panel/locale/zh.json create mode 100644 packages/client/ui-session-panel/package.json create mode 100644 packages/client/ui-session-panel/src/client/EnvironmentSection.tsx create mode 100644 packages/client/ui-session-panel/src/client/ProjectRow.module.css create mode 100644 packages/client/ui-session-panel/src/client/ProjectRow.tsx create mode 100644 packages/client/ui-session-panel/src/client/SessionPanel.module.css create mode 100644 packages/client/ui-session-panel/src/client/SessionPanel.tsx create mode 100644 packages/client/ui-session-panel/src/client/SessionPanelToggle.module.css create mode 100644 packages/client/ui-session-panel/src/client/SessionPanelToggle.tsx create mode 100644 packages/client/ui-session-panel/src/client/element-ids.ts create mode 100644 packages/client/ui-session-panel/src/client/index.ts create mode 100644 packages/client/ui-session-panel/src/client/locales.ts create mode 100644 packages/client/ui-session-panel/src/client/sections.ts create mode 100644 packages/client/ui-session-panel/src/client/slots.ts create mode 100644 packages/client/ui-session-panel/src/client/visibility.ts create mode 100644 packages/client/ui-session-panel/src/css-modules.d.ts create mode 100644 packages/client/ui-session-panel/src/index.ts create mode 100644 packages/client/ui-session-panel/tests/browser-plugin.client.spec.ts create mode 100644 packages/client/ui-session-panel/tests/components.client.spec.tsx create mode 100644 packages/client/ui-session-panel/tests/sections.client.spec.ts create mode 100644 packages/client/ui-session-panel/tests/visibility.client.spec.ts create mode 100644 packages/client/ui-session-panel/tsconfig.json create mode 100644 packages/client/ui-session-panel/tsdown.config.ts diff --git a/.agents/notes/implemented/feature/2026-11-05-session-panel.i18n.yaml b/.agents/notes/implemented/feature/2026-11-05-session-panel.i18n.yaml new file mode 100644 index 0000000000..4bd1f78eff --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-05-session-panel.i18n.yaml @@ -0,0 +1,28 @@ +# Bilingual-pair consistency record for 2026-11-05-session-panel.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-11-05-session-panel.md +/agent-note-session-panel-over-the-conversation-body-s-end-gutter: + en: e4548a86fa537e4a + zh: 87821d4285485faa +/agent-note-session-panel-over-the-conversation-body-s-end-gutter/problem: + en: c69d9843bc6f0b87 + zh: c31bb1b2b4d9b781 +/agent-note-session-panel-over-the-conversation-body-s-end-gutter/decision: + en: 547fe8129b027892 + zh: dc0807d782f551ae +/agent-note-session-panel-over-the-conversation-body-s-end-gutter/decision/docking-follows-the-transcript-gutter: + en: 150a7e8bf3ad556a + zh: c40fcf40af63b353 +/agent-note-session-panel-over-the-conversation-body-s-end-gutter/decision/sections-are-registrations-the-panel-draws-titles: + en: f8e69329e832c764 + zh: 2453aa8e794f46f5 +/agent-note-session-panel-over-the-conversation-body-s-end-gutter/decision/the-turn-rail-moves-to-the-start-edge: + en: 05a494885d439fde + zh: 1dc65e5266a9c7b1 +/agent-note-session-panel-over-the-conversation-body-s-end-gutter/alternatives-considered: + en: 9cf81cde02bf900b + zh: 549d92a260541e3d +/agent-note-session-panel-over-the-conversation-body-s-end-gutter/consequences: + en: c1f661c6a62953b6 + zh: 8642f081c2879307 diff --git a/.agents/notes/implemented/feature/2026-11-05-session-panel.md b/.agents/notes/implemented/feature/2026-11-05-session-panel.md new file mode 100644 index 0000000000..ca4b96e4ab --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-05-session-panel.md @@ -0,0 +1,47 @@ +# Agent Note: Session panel over the Conversation body's end gutter + +Status: implemented + +English | [中文](2026-11-05-session-panel.zh.md) + +## Problem + +Facts about the current Session — its project directory, the change requests it opened, and later its outputs — had no common home. Each owner added its own Session header button and, for anything larger than a menu, a right-sidebar tab: the forge change requests are one such tab. A sidebar tab takes width from the transcript while it shows, shows one tab at a time, and leaves the facts one click away from every message. The required surface is a summary the user can keep beside the conversation without covering it, that several plugins fill independently, that hides when there is no room, and that the user can show or hide from the Session header. + +## Decision + +[`dsh-client-ui-session-panel`](../../../../packages/client/ui-session-panel/README.md) adds a Session header toggle (`conversation.session.header.utilities`, order −10) and a floating panel that [`ui-conversation`](../../../../packages/client/ui-conversation/README.md) seats inside the main Conversation body as `conversation.session.panel`. The seat renders only for the main occurrence of an active Session, beside the width handles and outside the scrollport, so the panel neither scrolls with the transcript nor appears in embedded occurrences or on the blank home. + +### Docking follows the transcript gutter + +The panel docks only while the gutter between the transcript column and the body's end edge can hold it (344px: 48px clear of the column and its width handle, a 280px minimum width, and a 16px margin). The gutter, not the viewport width, decides because the column width is adaptive and user-draggable and the right sidebar shares the frame: the same viewport can leave 75px or 600px. The Conversation width controls already measure the body and resolve the column width, so they report the gutter after each measurement and drag frame into `ctx.uiConversation.layouts`, a per-Session source on the existing Conversation service. View activation reports whether the active View follows the transcript column; every View other than Chat fills the body, so the gutter reads zero there. + +The toggle and the panel read that source and one plugin-owned visibility state and decide the presentation with the same pure function. The toggle therefore reports `aria-expanded` truthfully and knows whether a press flips docking or opens the overlay, which a CSS-only container query cannot tell an element outside the body. + +Docking follows one persisted preference shared by every Session and defaults to on. Without room, a press opens a transient overlay for that Session above the transcript and the composer stack; it never changes the preference, and docking from a wide gutter closes it. Hiding automatically and overlaying on request keeps the transcript uncovered without making the facts unreachable on laptop widths. + +### Sections are registrations; the panel draws titles + +Each section is one list registration with `id`, `order`, and a required `label`. The panel projects the live registrations into titles, draws each title, and renders the section body with `renderSlot(..., { only: id })`; a CSS `:has()` rule hides a section whose body rendered nothing, so a section opts out by rendering nothing and no effect reports visibility to the owner. Trailing title controls are a keyed slot addressed by the section `id`, and a section that several plugins share declares its own row slot, as the built-in Environment section does with `conversation.session.panel.environment.row`. Marks that must stay visible while the panel is hidden go in an indicator list over the toggle. + +Rows from every contributor use the `PanelRow` primitive so icon, text, and trailing areas align across packages; a feature package cannot share its own row component with another feature package. + +### The turn rail moves to the start edge + +The turn rail used the end edge of the scrollport, which the docked panel now occupies. It moves to the start edge with its marks, focus ring, and preview mirrored; its existing 900px hiding rule still guarantees room beside the start-side width handle. + +## Alternatives considered + +- **A right-sidebar tab.** It already exists for change requests, but it narrows the transcript while shown, shows one tab at a time, and the [UI guidance](../../../skills/dsh-client-ui-ux/SKILL.md#reuse-before-adding) reserves the sidebar for content opened on demand rather than a resident summary. +- **The dock kit's floating window.** `FloatLayer` windows are draggable, resizable, and positioned in viewport coordinates; a summary anchored to the transcript gutter needs none of that and would have to fight the window's own placement rules. +- **Viewport-width breakpoints.** The transcript width is adaptive and draggable and the right sidebar takes a variable track, so a viewport breakpoint either covers the transcript or hides the panel with room to spare. +- **CSS-only hiding with a click-time read.** A container query on the gutter can hide the docked panel, and the toggle could read the computed result when pressed, as the background-job trigger does. The toggle would still render without knowing whether the panel shows, so `aria-expanded` and its tooltip would be wrong whenever the preference says dock but the gutter is too narrow. +- **Squeezing the transcript to make room.** Docking on laptop widths by moving the transcript column aside changes the centered column, the composer, and both width handles; it remains a separate layout decision. +- **A Session-scoped standard hook for the layout.** Adding `useConversationLayout` to every Session-scoped Slot made every component fixture in the client restate it; the layout has two readers, so a source on the existing Conversation service serves them without widening the standard props. + +## Consequences + +- With the default transcript width the body must be about 1608px wide to dock, so laptop widths use the overlay; the panel never covers the transcript unless the user opens it. +- Sections from independent plugins share one surface, ordering, and title style without depending on each other, and an occupied section id can be replaced by a higher-priority registration. +- The Conversation width controls gained one callback and the Conversation service one per-Session source; the composer stack height now lands on the content body so chrome outside the scrollport can read it. +- The turn rail's position changed for every user; its behavior and hiding rule did not. diff --git a/.agents/notes/implemented/feature/2026-11-05-session-panel.zh.md b/.agents/notes/implemented/feature/2026-11-05-session-panel.zh.md new file mode 100644 index 0000000000..136ceff8a0 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-05-session-panel.zh.md @@ -0,0 +1,47 @@ +# Agent Note: 停靠在对话正文末端留白的会话面板 + +Status: implemented + +[English](2026-11-05-session-panel.md) | 中文 + +## Problem + +与当前会话相关的信息(项目目录、它开出的变更请求,以及之后的产物)没有统一的位置。各自的拥有者分别加会话标题栏按钮,内容一多就再开一个右侧栏标签页,forge 的变更请求就是这样一个标签页。侧栏标签页显示时占用正文宽度,一次只显示一个,而且每条消息之外都要多点一次才能看到。需要的界面是:可以放在对话旁边常驻而不遮挡正文;多个插件各自填充;没有空间时自动隐藏;用户可以从会话标题栏显示或隐藏。 + +## Decision + +[`dsh-client-ui-session-panel`](../../../../packages/client/ui-session-panel/README.zh.md) 新增一个会话标题栏开关(`conversation.session.header.utilities`,order −10)和一块悬浮面板,由 [`ui-conversation`](../../../../packages/client/ui-conversation/README.zh.md) 以 `conversation.session.panel` 落位在主对话正文内。落位只为活跃会话的主 occurrence 渲染,与宽度拖拽条同层、位于滚动容器之外,因此面板不随正文滚动,也不会出现在嵌入式 occurrence 或空白首页。 + +### 停靠取决于正文留白 + +只有正文列到正文末端边缘的留白放得下面板时才停靠(344px:与正文列及其宽度拖拽条保持 48px,最小宽度 280px,外加 16px 边距)。判断依据是留白而不是视口宽度,因为正文列宽度可自适应、可由用户拖拽,右侧栏也会占用框架宽度:同一个视口可能只剩 75px,也可能有 600px。Conversation 宽度控件本来就测量正文并计算正文列宽度,因此它在每次测量和拖拽帧后把留白上报给 `ctx.uiConversation.layouts`,这是现有 Conversation 服务上的一个按会话划分的 source。View 激活时上报当前 View 是否跟随正文列;Chat 以外的 View 都占满正文,所以此时留白读数为零。 + +开关和面板读取同一个 source 和同一份插件持有的可见性状态,并用同一个纯函数决定呈现方式。因此开关能如实报告 `aria-expanded`,也知道按下后是切换停靠还是打开浮层;纯 CSS 的容器查询无法把结果告诉正文之外的元素。 + +停靠遵循所有会话共用的一个持久化偏好,默认开启。没有空间时,按下开关会为该会话在正文和 composer 区域上方打开临时浮层;它从不改变偏好,宽留白下切换停靠也会关闭浮层。自动隐藏加按需浮层,既保证正文不被遮挡,也让笔记本宽度下的信息依然可达。 + +### 分栏是注册项;面板绘制标题 + +每个分栏是一次 list 注册,带 `id`、`order` 和必填的 `label`。面板把实时注册投影成标题并逐个绘制,再用 `renderSlot(..., { only: id })` 渲染分栏正文;CSS `:has()` 规则隐藏正文没有渲染内容的分栏,因此分栏不渲染任何内容即可退出,不需要 effect 向拥有者上报可见性。标题尾部控件是以分栏 `id` 为键的 keyed slot;多个插件共用的分栏声明自己的行 slot,内置「环境」分栏就以 `conversation.session.panel.environment.row` 这样做。面板隐藏时也要可见的标记放进开关上的角标列表。 + +所有贡献方的行都使用 `PanelRow` 原语,使不同包的图标、文字与尾部区域对齐;功能包之间不能共享各自的行组件。 + +### 轮次轨道移到起始边 + +轮次轨道原先贴在滚动容器末端边缘,停靠面板现在占用这里。轨道连同刻度、焦点环和预览镜像到起始边;原有的 900px 隐藏规则仍保证它旁边有足够空间容纳起始侧的宽度拖拽条。 + +## Alternatives considered + +- **右侧栏标签页。** 变更请求已有这种实现,但它显示时会压窄正文,一次只显示一个标签页,而且 [UI 指南](../../../skills/dsh-client-ui-ux/SKILL.md#reuse-before-adding)把侧栏留给按需打开的内容,而不是常驻摘要。 +- **dock kit 的悬浮窗。** `FloatLayer` 窗口可拖拽、可缩放、按视口坐标定位;锚定在正文留白的摘要用不上这些能力,还要对抗窗口自身的定位规则。 +- **按视口宽度断点。** 正文宽度自适应、可拖拽,右侧栏占用可变宽度,视口断点要么遮挡正文,要么在空间充足时也隐藏面板。 +- **纯 CSS 隐藏加点击时读取。** 对留白做容器查询可以隐藏停靠面板,开关在按下时读取计算结果,与后台任务按钮的做法相同。但开关渲染时仍不知道面板是否显示,偏好为停靠而留白不足时,`aria-expanded` 与提示文字都会出错。 +- **挤压正文腾出空间。** 在笔记本宽度下把正文列移开来停靠,会改变居中的正文列、composer 和两侧宽度拖拽条;这仍是另一项布局决策。 +- **会话作用域标准 hook。** 给每个会话作用域 Slot 增加 `useConversationLayout`,会让客户端所有组件测试夹具都要补上它;布局只有两个读取方,所以放在现有 Conversation 服务上的 source 即可满足,无需扩大标准 props。 + +## Consequences + +- 在默认正文宽度下,对话区要约 1608px 宽才能停靠,因此笔记本宽度使用浮层;除非用户主动打开,面板不会遮挡正文。 +- 独立插件的分栏共享同一界面、排序和标题样式,彼此不依赖;已占用的分栏 id 可以被更高优先级的注册替换。 +- Conversation 宽度控件多了一个回调,Conversation 服务多了一个按会话划分的 source;composer 区域高度现在写在正文容器上,滚动容器之外的界面元素也能读取。 +- 轮次轨道的位置对所有用户都变了;行为和隐藏规则不变。 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 77ccb897b6..a495b7a44b 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -4984,6 +4984,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-client-ui-schedule` | — | [`packages/client/ui-schedule/src/index.ts`](../packages/client/ui-schedule/src/index.ts) | | `@deepseek-ai/dsh-client-ui-secret-mask` | — | [`packages/client/ui-secret-mask/src/index.ts`](../packages/client/ui-secret-mask/src/index.ts) | | `@deepseek-ai/dsh-client-ui-session` | — | [`packages/client/ui-session/src/index.ts`](../packages/client/ui-session/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-session-panel` | — | [`packages/client/ui-session-panel/src/index.ts`](../packages/client/ui-session-panel/src/index.ts) | | `@deepseek-ai/dsh-client-ui-settings` | — | [`packages/client/ui-settings/src/index.ts`](../packages/client/ui-settings/src/index.ts) | | `@deepseek-ai/dsh-client-ui-settings-agent-loop` | — | [`packages/client/ui-settings-agent-loop/src/index.ts`](../packages/client/ui-settings-agent-loop/src/index.ts) | | `@deepseek-ai/dsh-client-ui-settings-general` | — | [`packages/client/ui-settings-general/src/index.ts`](../packages/client/ui-settings-general/src/index.ts) | diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 4d4dde7b7a..924e6c8450 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -4986,6 +4986,7 @@ export interface Config { | `@deepseek-ai/dsh-client-ui-schedule` | — | [`packages/client/ui-schedule/src/index.ts`](../packages/client/ui-schedule/src/index.ts) | | `@deepseek-ai/dsh-client-ui-secret-mask` | — | [`packages/client/ui-secret-mask/src/index.ts`](../packages/client/ui-secret-mask/src/index.ts) | | `@deepseek-ai/dsh-client-ui-session` | — | [`packages/client/ui-session/src/index.ts`](../packages/client/ui-session/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-session-panel` | — | [`packages/client/ui-session-panel/src/index.ts`](../packages/client/ui-session-panel/src/index.ts) | | `@deepseek-ai/dsh-client-ui-settings` | — | [`packages/client/ui-settings/src/index.ts`](../packages/client/ui-settings/src/index.ts) | | `@deepseek-ai/dsh-client-ui-settings-agent-loop` | — | [`packages/client/ui-settings-agent-loop/src/index.ts`](../packages/client/ui-settings-agent-loop/src/index.ts) | | `@deepseek-ai/dsh-client-ui-settings-general` | — | [`packages/client/ui-settings-general/src/index.ts`](../packages/client/ui-settings-general/src/index.ts) | diff --git a/docs/module-graph.md b/docs/module-graph.md index e5f11c68b4..ef28563415 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -191,6 +191,7 @@ flowchart TD pkg_client_ui_schedule["client-ui-schedule"] pkg_client_ui_secret_mask["client-ui-secret-mask"] pkg_client_ui_session["client-ui-session"] + pkg_client_ui_session_panel["client-ui-session-panel"] pkg_client_ui_settings["client-ui-settings"] pkg_client_ui_settings_account["client-ui-settings-account"] pkg_client_ui_settings_agent_loop["client-ui-settings-agent-loop"] @@ -1600,6 +1601,7 @@ flowchart TD | [`client-ui-schedule`](../packages/client/ui-schedule) | `client` | — | | [`client-ui-secret-mask`](../packages/client/ui-secret-mask) | `client` | — | | [`client-ui-session`](../packages/client/ui-session) | `client` | — | +| [`client-ui-session-panel`](../packages/client/ui-session-panel) | `client` | — | | [`client-ui-settings`](../packages/client/ui-settings) | `client` | — | | [`client-ui-settings-account`](../packages/client/ui-settings-account) | `client` | — | | [`client-ui-settings-agent-loop`](../packages/client/ui-settings-agent-loop) | `client` | — | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 62a0ff3872..faf8d00c0c 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -193,6 +193,7 @@ flowchart TD pkg_client_ui_schedule["client-ui-schedule"] pkg_client_ui_secret_mask["client-ui-secret-mask"] pkg_client_ui_session["client-ui-session"] + pkg_client_ui_session_panel["client-ui-session-panel"] pkg_client_ui_settings["client-ui-settings"] pkg_client_ui_settings_account["client-ui-settings-account"] pkg_client_ui_settings_agent_loop["client-ui-settings-agent-loop"] @@ -1602,6 +1603,7 @@ flowchart TD | [`client-ui-schedule`](../packages/client/ui-schedule) | `client` | — | | [`client-ui-secret-mask`](../packages/client/ui-secret-mask) | `client` | — | | [`client-ui-session`](../packages/client/ui-session) | `client` | — | +| [`client-ui-session-panel`](../packages/client/ui-session-panel) | `client` | — | | [`client-ui-settings`](../packages/client/ui-settings) | `client` | — | | [`client-ui-settings-account`](../packages/client/ui-settings-account) | `client` | — | | [`client-ui-settings-agent-loop`](../packages/client/ui-settings-agent-loop) | `client` | — | diff --git a/docs/subsystems/slots.i18n.yaml b/docs/subsystems/slots.i18n.yaml index a101ff98ea..a6e84e3f31 100644 --- a/docs/subsystems/slots.i18n.yaml +++ b/docs/subsystems/slots.i18n.yaml @@ -3,8 +3,8 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/slots.md /web-client-slots: - en: 15c49af3ed8b57ff - zh: e7f9189de6f4334c + en: c3e0c40beeda0651 + zh: a94d81520205694c /web-client-slots/declaration-and-lifecycle: en: f2d2c0d3b8f14ec7 zh: 441ed13ff3f81d2a diff --git a/docs/subsystems/slots.md b/docs/subsystems/slots.md index d13357d0b2..48c059b772 100644 --- a/docs/subsystems/slots.md +++ b/docs/subsystems/slots.md @@ -16,6 +16,8 @@ The root-scoped lists `sidebar.panellist.actions`, `conversation.session.header. [ui-settings](../../packages/client/ui-settings/README.md#filling-the-settings-slots) documents the settings page and navigation-icon extension points. +[ui-session-panel](../../packages/client/ui-session-panel/README.md#contribute-a-section) documents the Session panel's section, title-control, row, and toggle-indicator extension positions. + ## Declaration and lifecycle `SlotMap` is the compile-time registry. A package declaration-merges the key, cardinality, scope, owner props, keyed props, and optional slot-level inject face. The runtime declaration is the matching `children` entry on the component that owns the render location. @@ -145,6 +147,8 @@ root [AppFrame] │ ├─ conversation.session.header.lineage │ ├─ conversation.session.header.actions │ ├─ conversation.session.header.utilities +│ │ └─ id=session-panel [SessionPanelToggle] +│ │ └─ conversation.session.panel.indicator [list, inline] │ ├─ conversation.session.header.views.actions │ └─ conversation.session.header.corner └─ calls Factory: conversation.content @@ -200,7 +204,12 @@ Factory: conversation.content [ConversationContent] ├─ conversation.hero.workspace │ └─ conversation.hero.workspace.directoryFlow ├─ conversation.hero.agentPreset -└─ conversation.hero.options +├─ conversation.hero.options +└─ conversation.session.panel [SessionPanel] + ├─ conversation.session.panel.section [list] + │ └─ id=environment [EnvironmentSection] + │ └─ conversation.session.panel.environment.row [list] + └─ conversation.session.panel.section.actions [keyed] Factory: conversation.chat.user.content [UserContent] ├─ conversation.chat.user.images [MessageImages] diff --git a/docs/subsystems/slots.zh.md b/docs/subsystems/slots.zh.md index 61014d4418..3a9a70b2d1 100644 --- a/docs/subsystems/slots.zh.md +++ b/docs/subsystems/slots.zh.md @@ -16,6 +16,8 @@ root 作用域的 list `sidebar.panellist.actions`、`conversation.session.heade [ui-settings](../../packages/client/ui-settings/README.zh.md#filling-the-settings-slots) 记录设置页面与导航图标扩展点。 +[ui-session-panel](../../packages/client/ui-session-panel/README.zh.md#contribute-a-section) 记录会话面板的分栏、标题控件、行与开关角标扩展位置。 + ## 声明与生命周期 `SlotMap` 是编译期注册表。包通过声明合并写入 key、cardinality(基数)、scope、owner props、keyed props 与可选的 slot 级 inject face。运行时声明则是拥有该渲染位置的组件在 `children` 中给出的对应条目。 @@ -147,6 +149,8 @@ root [AppFrame] │ ├─ conversation.session.header.lineage │ ├─ conversation.session.header.actions │ ├─ conversation.session.header.utilities +│ │ └─ id=session-panel [SessionPanelToggle] +│ │ └─ conversation.session.panel.indicator [list, inline] │ ├─ conversation.session.header.views.actions │ └─ conversation.session.header.corner └─ calls Factory: conversation.content @@ -202,7 +206,12 @@ Factory: conversation.content [ConversationContent] ├─ conversation.hero.workspace │ └─ conversation.hero.workspace.directoryFlow ├─ conversation.hero.agentPreset -└─ conversation.hero.options +├─ conversation.hero.options +└─ conversation.session.panel [SessionPanel] + ├─ conversation.session.panel.section [list] + │ └─ id=environment [EnvironmentSection] + │ └─ conversation.session.panel.environment.row [list] + └─ conversation.session.panel.section.actions [keyed] Factory: conversation.chat.user.content [UserContent] ├─ conversation.chat.user.images [MessageImages] diff --git a/packages/bundle/web-app/cordis.patch.yml b/packages/bundle/web-app/cordis.patch.yml index 59b3473ba5..310b70dc90 100644 --- a/packages/bundle/web-app/cordis.patch.yml +++ b/packages/bundle/web-app/cordis.patch.yml @@ -433,6 +433,11 @@ - id: ui-schedule name: '@deepseek-ai/dsh-client-ui-schedule' + # Session panel: the header toggle and the floating panel over the main + # Conversation body, with the Environment section other plugins extend. + - id: ui-session-panel + name: '@deepseek-ai/dsh-client-ui-session-panel' + # Goal surface: GoalBar in the input dock over the goal session projection. - id: ui-goal name: '@deepseek-ai/dsh-client-ui-goal' diff --git a/packages/bundle/web-app/package.json b/packages/bundle/web-app/package.json index dd4860c5c0..18a9d5b95f 100644 --- a/packages/bundle/web-app/package.json +++ b/packages/bundle/web-app/package.json @@ -105,6 +105,7 @@ "@deepseek-ai/dsh-client-ui-reference": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-schedule": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-panel": "workspace:*", "@deepseek-ai/dsh-client-ui-secret-mask": "workspace:*", "@deepseek-ai/dsh-client-ui-session": "workspace:*", "@deepseek-ai/dsh-client-ui-settings": "workspace:*", diff --git a/packages/client/README.i18n.yaml b/packages/client/README.i18n.yaml index f77d3835d7..07c98c8d89 100644 --- a/packages/client/README.i18n.yaml +++ b/packages/client/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1eb35b015a6c423f zh: a8a3dceee2c9e943 /client-web-gui-browser-half/packages: - en: 2165938f26300774 - zh: 5f739534a8509545 + en: 62d58fd9b8fdb4e7 + zh: 8b6c078927a32e9d /client-web-gui-browser-half/related-documentation: en: d1d506e68fab7333 zh: 1a90fe6f3f8f24a9 diff --git a/packages/client/README.md b/packages/client/README.md index 3047a181c1..ca160f395e 100644 --- a/packages/client/README.md +++ b/packages/client/README.md @@ -68,6 +68,7 @@ The kernel packages boot and serve the page; the UI feature packages present it. | [`ui-subagent/`](ui-subagent/README.md) | Provides subagent navigation, child transcript states, and inline references | — | | [`ui-jobs/`](ui-jobs/README.md) | Lists this session's background jobs with on-demand streaming record panels | — | | [`ui-schedule/`](ui-schedule/README.md) | Provides the sidebar Automation tasks page and right Sidebar task tab, which create, edit, run, pause, resume, and delete Host scheduled tasks, plus the Session header clock and row mark | — | +| [`ui-session-panel/`](ui-session-panel/README.md) | Adds the Session header toggle and the floating Session panel whose sections plugins register, with the Environment section | — | | [`ui-model-selection/`](ui-model-selection/README.md) | Provides model selection in conversation surfaces | — | | [`ui-permission-presets/`](ui-permission-presets/README.md) | Configures default permissions and switches the current session's access | — | | [`ui-plan/`](ui-plan/README.md) | Presents active plan-mode status and its exit control | — | diff --git a/packages/client/README.zh.md b/packages/client/README.zh.md index e327a717d9..de5301fc93 100644 --- a/packages/client/README.zh.md +++ b/packages/client/README.zh.md @@ -68,6 +68,7 @@ kind: "package-group" | [`ui-subagent/`](ui-subagent/README.zh.md) | 提供 subagent 导航、子级 transcript(文本记录)状态与内联引用 | — | | [`ui-jobs/`](ui-jobs/README.zh.md) | 列出本会话的后台任务,并提供按需展开的流式输出面板 | — | | [`ui-schedule/`](ui-schedule/README.zh.md) | 提供侧栏“自动化任务”页面与右侧栏任务页签,用于创建、编辑、立即运行、暂停、恢复和删除宿主的计划任务,并提供 Session 顶部时钟与行标记 | — | +| [`ui-session-panel/`](ui-session-panel/README.zh.md) | 提供会话标题栏开关与悬浮会话面板,分栏由插件注册,并内置「环境」分栏 | — | | [`ui-model-selection/`](ui-model-selection/README.zh.md) | 在对话界面中提供模型选择 | — | | [`ui-permission-presets/`](ui-permission-presets/README.zh.md) | 配置默认权限并切换当前会话的访问模式 | — | | [`ui-plan/`](ui-plan/README.zh.md) | 展示生效中的 plan mode 状态及其退出控件 | — | diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index 3120b6b576..20403ed74c 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -36,8 +36,8 @@ en: b1630d93a52f483e zh: 59cb81ca50ecffc4 /deepseek-ai-dsh-client-ui-chat/scroll-ownership: - en: dd4e69828096c3a0 - zh: 2a9bc370f44efcd7 + en: 1bede2217882f0bd + zh: af4b389545ac8840 /deepseek-ai-dsh-client-ui-chat/model-experience: en: c17b4dd43a61c569 zh: f7414309810c3a08 diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md index d845c15bbd..ce852e5b15 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -146,7 +146,7 @@ Chat waits for initial history before automatic content, scroll, or size updates Chat restores semantic anchors across history prepend and renderer remounts, with browser scroll anchoring disabled on its scrollport only while following the tail. Pinned scroll deliveries without reader movement, and reader input that reaches the floor within subpixel rounding, update follow ownership immediately, before subsequent layout changes can invalidate their floor. Other reader movement remains pending until the sampling interval or `scrollend`, even inside the follow threshold, so layout growth cannot erase small scroll gestures. Under completion-time folding, submitting transcript input or steering immediately restores tail following and clears an older pending reader sample. Under next-message folding, transcript input that no fold batch carries lands on one native animation; steering lands at once under either timing, because the running Turn keeps streaming above its echo. While the reader is pinned to the floor, `ResizeObserver` follows the new floor and selects the latest loaded Turn without reading row geometry. Once the reader moves away, flow-height changes preserve the top position and the reading-line geometry selects the active Turn. Turn-rail previews paint above sticky Markdown code-block banners, while the rail frame remains inside the transcript band above the composer. -The turn rail and back-to-bottom button sit outside the clipped transcript. They use the shared conversation scrollport for sticky positioning, or the Chat frame for absolute positioning when Chat owns its scrollport. The rail hides when the transcript's available width, excluding its horizontal padding, is at most 900px; the browser viewport width is not the criterion. +The turn rail and back-to-bottom button sit outside the clipped transcript. They use the shared conversation scrollport for sticky positioning, or the Chat frame for absolute positioning when Chat owns its scrollport. The rail sits at the scrollport's start edge, which leaves the end gutter to the [Session panel](../ui-session-panel/README.md), and its previews open toward the transcript. The rail hides when the transcript's available width, excluding its horizontal padding, is at most 900px; the browser viewport width is not the criterion. The transcript root uses `overflow-x: visible; overflow-y: clip`: vertical overflow is clipped without creating a scroll container. Sticky Markdown code banners and expanded compaction headers therefore retain the actual conversation scrollport as their reference when no nearer scrolling ancestor exists. Capped process groups and terminal sections keep their own scrollports. diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index 80402eadf2..8152e86cbc 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -146,7 +146,7 @@ Chat 等待初始历史就绪后,才允许自动内容、滚动或尺寸更新 Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点,并且只在跟随底部时禁用自己滚动区域的浏览器自动锚定。没有读者移动的贴底滚动事件,以及到达底部(容许小于 1px 的取整误差)的读者输入,会立即更新跟随归属,避免后续布局变化使其底部位置失效。其他读者移动即使位于跟随阈值内,也保持待处理直到采样周期或 `scrollend`,防止布局增长抵消小幅滚动操作。采用完成时收起时,提交正文输入或 steering 会立即恢复跟随底部,并清除先前待处理的读者滚动采样。采用下次消息时收起时,没有折叠批次承载的正文输入用一次原生动画落到底部;steering 在两种时机下都立即落到底部,因为运行中的 Turn 仍在其回显上方持续输出。读者跟随底部时,`ResizeObserver` 追随新的底部,并且无需读取行几何就选中最后一个已加载轮次;读者离开底部后,高度变化会保持顶部位置,再由阅读线几何选择活跃轮次。轮次导航预览位于 Markdown 代码块粘性头栏上方,而导航外框始终处于 composer 上方的 transcript 区域内。 -轮次轨道与回到底部按钮位于正文裁剪层外。它们相对共享会话滚动容器做 sticky 定位;Chat 自己持有滚动容器时,则相对 Chat 外框做 absolute 定位。正文扣除水平内边距后的可用宽度不超过 900px 时,隐藏轮次轨道;判断依据不是浏览器视口宽度。 +轮次轨道与回到底部按钮位于正文裁剪层外。它们相对共享会话滚动容器做 sticky 定位;Chat 自己持有滚动容器时,则相对 Chat 外框做 absolute 定位。轮次轨道贴在滚动容器的起始边,把末端留白让给[会话面板](../ui-session-panel/README.zh.md),预览朝正文方向弹出。正文扣除水平内边距后的可用宽度不超过 900px 时,隐藏轮次轨道;判断依据不是浏览器视口宽度。 正文根节点使用 `overflow-x: visible; overflow-y: clip`:裁剪纵向溢出,但不创建滚动容器。因此,在没有更近的滚动祖先时,Markdown 代码块的 sticky 头栏和展开的压缩摘要头栏仍以实际会话滚动容器为参照。限高过程组和终端区域保留各自的滚动容器。 diff --git a/packages/client/ui-chat/src/client/chat/TurnNavigator.module.css b/packages/client/ui-chat/src/client/chat/TurnNavigator.module.css index c4d495b8d6..2d8166ca68 100644 --- a/packages/client/ui-chat/src/client/chat/TurnNavigator.module.css +++ b/packages/client/ui-chat/src/client/chat/TurnNavigator.module.css @@ -30,7 +30,8 @@ position: absolute; top: calc(var(--turn-rail-band) / 2); - right: 12px; + /* The start edge: the end gutter belongs to the Session panel. */ + left: 12px; width: 28px; /* Fixed-pitch marks never compress: a ladder taller than the band scrolls inside this frame instead of pushing marks under the composer or above @@ -97,14 +98,14 @@ .mark::before { position: absolute; top: 50%; - right: 0; + left: 0; width: 20px; height: 2px; border-radius: 2px; background: var(--dsw-alias-border-l4); content: ''; transform: translateY(-50%) scaleX(0.6); - transform-origin: right center; + transform-origin: left center; transition: transform 140ms ease, background-color 140ms ease; } @@ -142,11 +143,11 @@ .mark:focus-visible::after { position: absolute; - inset: 0 0 0 auto; + inset: 0 auto 0 0; width: 20px; border-radius: inherit; outline: 1px solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); - /* The scroller clips the right edge; keep the marker's ring inside it. */ + /* The scroller clips the left edge; keep the marker's ring inside it. */ outline-offset: -1px; content: ''; } @@ -158,7 +159,7 @@ calc(var(--turn-preview-center) - var(--turn-preview-height) / 2), calc(100% - var(--turn-preview-height)) ); - right: calc(100% + 10px); + left: calc(100% + 10px); box-sizing: border-box; width: min(300px, calc(100cqw - 120px)); max-height: var(--turn-preview-height); @@ -194,7 +195,7 @@ } @keyframes dsh-turn-preview-enter { - from { opacity: 0; transform: translateX(4px); } + from { opacity: 0; transform: translateX(-4px); } to { opacity: 1; transform: translateX(0); } } diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index c88fda7554..06d21c9a63 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -21,8 +21,8 @@ en: cc4dafd1aae02468 zh: be6b67724b7ac4a3 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: bd2a85b9012fa3c3 - zh: e88d7e682e316a0e + en: 1d9c21bd934d1a3b + zh: 3c47d27ea72b2a2e /deepseek-ai-dsh-client-ui-conversation/temporary-composer-entries: en: 59cd63057dfb6eeb zh: b2e2c86e810b7bb8 diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 041aa0d5d4..25bc4dab22 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -120,6 +120,8 @@ Active transcripts in the main occurrence expose content-width drag handles in t The width-handle indicator follows the pointer only during a captured drag; ordinary hover leaves its position unchanged. +The main occurrence of an active Session also renders the `conversation.session.panel` seat inside its body, beside the width handles and outside the scrollport; embedded occurrences and the blank home omit it. Its occupant positions itself against the body, which carries the transcript axis and the composer stack height `--dsh-composer-height`. `ctx.uiConversation.layouts.source(sessionId)` publishes that Session's `ConversationLayout`: `endGutter` is the space between the transcript column's end edge and the body's end edge, written by the main width controls after each measurement and drag frame and reset to zero when they unmount. It stays zero while a View other than Chat, which fills the body, is active. + 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), the claimed slash command is an atomic leading chip that carries its claim, folder text references carry the folder glyph as an icon prefix, and the draft's text and semantic references are persisted by the per-Session Conversation store. QueueDock reads `next-turn` from the Session `inbox` projection, including cold recovered messages, and excludes only requestIds still owned by local transcript submissions. Other queued rows retain their normal display and actions. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews use the [UserText Factory](#sent-user-text) (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 in the ui-primitives `InlineEditor`, so line breaks survive re-editing. 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. In narrow browser settings, the busy-state Enter preference uses a smaller label gutter. Windows and macOS desktop windows retain the standard spacing. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index 0ac0d779d1..8f9964211f 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -120,6 +120,8 @@ Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染 宽度拖拽条的指示线只在已捕获指针的拖拽期间跟随指针,普通悬停不改变其位置。 +活跃 Session 的主 occurrence 还会在正文内渲染 `conversation.session.panel` 落位,与宽度拖拽条同层,位于滚动容器之外;嵌入式 occurrence 和空白首页不渲染它。占位组件相对正文定位,正文持有正文轴线与 composer 区域高度 `--dsh-composer-height`。`ctx.uiConversation.layouts.source(sessionId)` 发布该 Session 的 `ConversationLayout`:`endGutter` 是正文列末端边缘到正文末端边缘的距离,由主宽度控件在每次测量与拖拽帧后写入,控件卸载时归零。激活的是 Chat 以外的 View(这类 View 占满正文)时,它保持为零。 + 常驻 composer 在无 Session 与有 Session 之间保持挂载。输入空白字符会隐藏占位提示;没有附件的纯空白草稿无法发送。无 Session 时,同一个编辑器表面保持 inert,Workspace picker 连接 blank Session。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 是携带认领的行首原子 chip,文件夹文本引用以图标前缀携带文件夹图形,草稿文字和引用语义字段由逐 Session Conversation store 持久化。QueueDock 从 Session 的 `inbox` 投影读取 `next-turn`,包含从冷状态恢复的消息,仅排除仍由本地 transcript 提交承接的 requestId。其他排队行保留正常展示和操作。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览使用 [UserText Factory](#sent-user-text)(wire 会话形式折叠为其标签),并按原始附件顺序展示本地或持久化的图片和文件。图片使用缩略图,文件使用紧凑的名称与大小卡片。编辑态在 ui-primitives 的 `InlineEditor` 中展示字面发送文本,因此重新编辑不会丢失换行。持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。 composer 键盘映射经斜杠流水线裁决触发菜单的按键——Tab 确认高亮补全项(可下钻项则下钻),Escape 与 Shift+Tab 离开菜单且不选定——其余按键交给编辑器自身。 接管键盘的浮层通过 `SessionInput.focus()` 把键盘还回来,该路径走 Lexical 自己的 focus,因此光标回到草稿原来的位置而不是开头。 窄屏浏览器设置中,繁忙时 Enter 偏好的标签与控件间距缩小;Windows 和 macOS 桌面窗口保留标准间距。 diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index aae71928be..bad863ff72 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -45,7 +45,7 @@ import { ConversationSession, ConversationSessionHeader } from './skeleton/Conve import { InputBar } from './skeleton/InputBar.tsx' import { todoDockEntry } from './skeleton/TodoPanel.tsx' import { installStopShortcut } from './stop-shortcut.ts' -import { TRAJECTORY_VIEW_ID, resolveActiveView } from './view-selection.ts' +import { DEFAULT_VIEW_ID, TRAJECTORY_VIEW_ID, resolveActiveView } from './view-selection.ts' import { createViewPins } from './view-pins.ts' import { en, ja, es, fr, de, ru, pt, NS, zh, type ConversationKey } from './locales.ts' import { CONVERSATION_SETTINGS_NAMESPACE, type ConversationSettings } from '../submission-settings.ts' @@ -221,7 +221,10 @@ export function apply(ctx: Context, config: Config = Config({})): void { } const activateView = (sessionId: SessionId, preferred: string | null): void => { const active = resolveActiveView(viewTabs(), preferred) - if (active !== undefined) uiConversation.binding(sessionId).activate(active.id) + if (active === undefined) return + uiConversation.binding(sessionId).activate(active.id) + // Chat is the View laid out on the transcript column. + uiConversation.layouts.activate(sessionId, active.id === DEFAULT_VIEW_ID) } const restoreView = (sessionId: SessionId): void => { activateView(sessionId, readConversationViewPreference(sessionId)) @@ -354,6 +357,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { 'conversation.hero.workspace': { kind: 'single', scope: 'root' }, 'conversation.hero.agentPreset': { kind: 'single', scope: 'session-maybe' }, 'conversation.hero.options': { kind: 'list', scope: 'session' }, + 'conversation.session.panel': { kind: 'single', scope: 'session' }, }, slots: { views: { scope: 'session' }, @@ -363,6 +367,9 @@ export function apply(ctx: Context, config: Config = Config({})): void { hooks: { composerBlock: sessionId === undefined ? ABSENT_BLOCK : composerBlocks.storeFor(sessionId), }, + reportEndGutter: (endGutter) => { + if (sessionId !== undefined) uiConversation.layouts.measure(sessionId, endGutter) + }, selectWorkspace: workspaceId => workspaceNavigation.openWorkspace(workspaceId, (nextId) => { if (sessionId !== undefined && nextId !== sessionId) { const from = inputHub.shell(sessionId) diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index e7ae7285ab..9dbe00d8bb 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -279,6 +279,13 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { scope: 'session' owner: ConversationHeaderCornerOwnerProps } + /** + * One floating panel over the main Conversation body's end gutter. It renders + * only for the main occurrence of a Session in its active phase, never for an + * embedded occurrence or the blank home; the occupant positions itself against + * the body and reads `ctx.uiConversation.layouts` to keep clear of the transcript. + */ + 'conversation.session.panel': { kind: 'single'; scope: 'session'; owner: ConversationSessionPanelOwnerProps } /** Rows of the View tab row's More menu; the header shows More only while this list has registrations. */ 'conversation.session.header.views.actions': { kind: 'list'; scope: 'root'; owner: ConversationViewActionsOwnerProps } /** Registered Conversation target Views, rendered one at a time. */ @@ -377,6 +384,7 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { 'conversation.hero.workspace': { kind: 'single'; scope: 'root' } 'conversation.hero.agentPreset': { kind: 'single'; scope: 'session-maybe' } 'conversation.hero.options': { kind: 'list'; scope: 'session' } + 'conversation.session.panel': { kind: 'single'; scope: 'session' } } inject: ConversationInjected locale: 'conversation' @@ -423,6 +431,23 @@ export interface ConversationHeaderActionOwnerProps { children?: never } +/** The Session panel's occupant derives its state from standard Session props. */ +export interface ConversationSessionPanelOwnerProps { + /** Marker field: the occupant receives no owner-specific values. */ + children?: never +} + +/** Geometry that floating chrome over the main Conversation body keeps clear of. */ +export interface ConversationLayout { + /** + * Inline space in CSS px between the transcript column's end edge and the + * body's end edge. Zero before the first measurement, while the main body + * shows another Session, and while the active View does not follow the + * transcript column (every View other than Chat). + */ + readonly endGutter: number +} + /** The header corner's occupant derives its state from standard Session props. */ export interface ConversationHeaderCornerOwnerProps { /** Marker field: the occupant receives no owner-specific values. */ @@ -472,6 +497,12 @@ export interface ConversationInjected { selectWorkspace: (workspaceId: WorkspaceId) => Promise /** Session-addressed composer block source, or the stable absent source. */ hooks: { composerBlock: ObservableSnapshot } + /** + * Record the end gutter the main body measured for this occurrence's Session; + * no effect without a Session. + * @param endGutter - space between the transcript column's end edge and the body's end edge, in CSS px. + */ + reportEndGutter: (endGutter: number) => void } /** Business callbacks injected into the strict Session body. */ @@ -664,6 +695,12 @@ export interface ConversationWidthControlsInputProps { container: HTMLDivElement | null /** Current body phase; handles render only for an active transcript. */ phase: ConversationContentInputProps['phase'] + /** + * Receive the end gutter after each measurement and drag frame, and zero when + * the controls unmount. + * @param endGutter - space between the transcript column's end edge and the body's end edge, in CSS px. + */ + onEndGutter: (endGutter: number) => void } /** Full props of the reusable Conversation Factory definition. */ diff --git a/packages/client/ui-conversation/src/client/conversation/assembly.ts b/packages/client/ui-conversation/src/client/conversation/assembly.ts index 233a72e23f..d879921d9b 100644 --- a/packages/client/ui-conversation/src/client/conversation/assembly.ts +++ b/packages/client/ui-conversation/src/client/conversation/assembly.ts @@ -26,6 +26,7 @@ import { ConversationViewRegistry } from './view-registry.ts' import { ConversationGroupRegistry } from './group-registry.ts' import { ConversationInteractionRegistry } from './interaction-registry.ts' import { UserTextRegistry } from './user-text-registry.ts' +import { ConversationLayouts } from './layouts.ts' /** Observable faces published for one Session's Conversation assembly. */ export interface ConversationBinding { @@ -211,6 +212,8 @@ export class UiConversation extends Service { readonly userText: UserTextRegistry /** Plugin-owned handlers for selection and context-menu gestures. */ readonly interactions: ConversationInteractionRegistry + /** Main Conversation body geometry per Session; the Conversation shell writes it and floating chrome reads it. */ + readonly layouts: ConversationLayouts = new ConversationLayouts() private readonly bindings = new WeakMapWithValues() private readonly images: HistoricalImageCache diff --git a/packages/client/ui-conversation/src/client/conversation/layouts.ts b/packages/client/ui-conversation/src/client/conversation/layouts.ts new file mode 100644 index 0000000000..9caa7c35cf --- /dev/null +++ b/packages/client/ui-conversation/src/client/conversation/layouts.ts @@ -0,0 +1,72 @@ +/** Per-Session geometry of the main Conversation body, published through `ctx.uiConversation.layouts`. */ +import { createSnapshotStore, type ObservableSnapshot, type SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { ConversationLayout } from '../contract/slots.ts' + +const NO_LAYOUT: ConversationLayout = Object.freeze({ endGutter: 0 }) + +interface LayoutEntry { + /** Last end gutter the main body's width controls measured, in CSS px. */ + measured: number + /** Whether the Session's active View follows the transcript column; false before the first activation. */ + followsTranscript: boolean + readonly store: SnapshotStore +} + +/** + * Layout facts of the main Conversation body, kept per Session for the + * lifetime of the Conversation plugin. The Conversation shell writes them: + * the main body's width controls report the measured end gutter, and View + * activation reports whether the active View follows the transcript column. + * The published gutter is zero while it does not, because such a View fills + * the body. Floating chrome reads one Session's facts through `source`. + */ +export class ConversationLayouts { + private readonly entries = new Map() + + /** + * Read one Session's layout source. + * @param sessionId - Session whose main body geometry is read. + * @returns a source whose identity is stable per Session and whose snapshot keeps its identity until the gutter changes. + */ + source(sessionId: SessionId): ObservableSnapshot { + return this.entryOf(sessionId).store + } + + /** + * Record the end gutter the main body measured while showing a Session. + * @param sessionId - Session the main body shows. + * @param endGutter - space between the transcript column's end edge and the body's end edge, in CSS px. + */ + measure(sessionId: SessionId, endGutter: number): void { + const entry = this.entryOf(sessionId) + entry.measured = Math.max(0, endGutter) + this.publish(entry) + } + + /** + * Record whether the View a Session activated follows the transcript column. + * @param sessionId - Session whose View changed. + * @param followsTranscript - true for a View laid out on the transcript column. + */ + activate(sessionId: SessionId, followsTranscript: boolean): void { + const entry = this.entryOf(sessionId) + entry.followsTranscript = followsTranscript + this.publish(entry) + } + + private entryOf(sessionId: SessionId): LayoutEntry { + let entry = this.entries.get(sessionId) + if (entry === undefined) { + entry = { measured: 0, followsTranscript: false, store: createSnapshotStore(NO_LAYOUT) } + this.entries.set(sessionId, entry) + } + return entry + } + + private publish(entry: LayoutEntry): void { + const endGutter = entry.followsTranscript ? entry.measured : 0 + if (entry.store.getSnapshot().endGutter === endGutter) return + entry.store.set(endGutter === 0 ? NO_LAYOUT : { endGutter }) + } +} diff --git a/packages/client/ui-conversation/src/client/index.ts b/packages/client/ui-conversation/src/client/index.ts index 8a1b95e941..069142b75c 100644 --- a/packages/client/ui-conversation/src/client/index.ts +++ b/packages/client/ui-conversation/src/client/index.ts @@ -86,8 +86,8 @@ export type { ComposerFileAttachment, ComposerImageAttachment, DraftFileUpload, DraftFileUploads, ComposerBarInjected, ComposerBarOwnerProps, ComposerBarProps, ComposerChainProps, ConversationHeaderActionOwnerProps, ConversationHeaderCornerOwnerProps, ConversationHeaderLineageOwnerProps, - ConversationContentInputProps, ConversationContentProps, - ConversationInjected, ConversationSessionHeaderInjected, ConversationSessionHeaderSlotProps, + ConversationContentInputProps, ConversationContentProps, ConversationLayout, + ConversationInjected, ConversationSessionPanelOwnerProps, ConversationSessionHeaderInjected, ConversationSessionHeaderSlotProps, ConversationSessionInjected, ConversationSessionSlotProps, ConversationSlotProps, ConversationViewActionEntry, ConversationViewActionsOwnerProps, ConversationViewsProps, ConversationWidthControlsInputProps, ConversationWidthControlsProps, diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx index 4c6b8e6578..1f3f6ab5b6 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx @@ -23,7 +23,7 @@ export function ConversationContent(props: ConversationContentProps) { const { sessionId, phase, hero, useSession, useSessions, useSessionStatus, useWorkspaces, useInput, useComposerBlock, renderSlot, renderSlotChain, - selectWorkspace, t, useFactorySlot, + selectWorkspace, reportEndGutter, t, useFactorySlot, } = props const session = useSession(snapshot => snapshot) const Views = useFactorySlot('views', ConversationSessionView) @@ -42,22 +42,25 @@ export function ConversationContent(props: ConversationContentProps) { const [pendingWorkspaceId, setPendingWorkspaceId] = useState() const pickerAnchor = useRef(null) - // Publishes the two live measurements floating View chrome reads off the - // scroll body: the seat's height as --dsh-composer-height, so controls clear - // the composer as it grows, and the scrollport's own height as + // Publishes the two live measurements floating chrome reads: the seat's + // height as --dsh-composer-height, so controls clear the composer as it + // grows, and the scrollport's own height as // --dsh-conversation-viewport-height, so a control can sit in the band the - // seat leaves visible. Callback ref, not an effect; stable identity prevents - // observer churn while the first blank session fills the resident body - // outlet. + // seat leaves visible. They land on the content body, so View chrome inside + // the scrollport and the Session panel beside it read the same values. + // Callback ref, not an effect; stable identity prevents observer churn while + // the first blank session fills the resident body outlet. const seatObserver = useRef(null) const seatResizeRef = useCallback((seat: HTMLDivElement | null): void => { seatObserver.current?.disconnect() seatObserver.current = null const scroller = seat?.parentElement ?? null if (seat === null || scroller === null) return + /* v8 ignore next -- the seat always renders inside the content body. */ + const target = scroller.closest('[data-conversation-content]') ?? scroller seatObserver.current = new ResizeObserver(() => { - scroller.style.setProperty('--dsh-composer-height', `${seat.offsetHeight}px`) - scroller.style.setProperty( + target.style.setProperty('--dsh-composer-height', `${seat.offsetHeight}px`) + target.style.setProperty( '--dsh-conversation-viewport-height', `${scroller.clientHeight}px`, ) @@ -204,7 +207,9 @@ export function ConversationContent(props: ConversationContentProps) {
), })} - + + {props.variant === 'main' && sessionId !== undefined && phase === 'active' + && renderSlot('conversation.session.panel', {})}
) } diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx index 53f42c199f..1b35ee6137 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx @@ -20,7 +20,12 @@ function readWidthPreference(): number | null { return Number.isFinite(value) && value > 0 ? value : null } -/** Resolve the width displayed for one measured Conversation column. */ +/** + * Resolve the width displayed for one measured Conversation column. + * @param columnWidth - measured body width in CSS px. + * @param preference - persisted dragged width, or null for the adaptive default. + * @returns the transcript column width in CSS px. + */ function resolveContentWidth(columnWidth: number, preference: number | null): number { const max = Math.max(CONTENT_MIN, columnWidth - CONTENT_EDGE_BUDGET) if (preference !== null) return Math.min(Math.max(preference, CONTENT_MIN), max) @@ -129,11 +134,14 @@ function WidthHandle(props: { } /** - * Install the main Conversation width axis and render its drag handles. + * Install the main Conversation width axis, report its end gutter, and render its drag handles. * @param props - Mounted Conversation body and current presentation phase. * @returns two active-phase width handles, or no controls outside the active phase. */ -export function ConversationWidthControls({ container, phase }: ConversationWidthControlsProps) { +export function ConversationWidthControls({ container, phase, onEndGutter }: ConversationWidthControlsProps) { + // The observer outlives renders; it reports through the latest callback. + const report = useRef(onEndGutter) + report.current = onEndGutter const publishWidths = useCallback((container: HTMLDivElement): void => { const target = container.parentElement ?? container const column = container.offsetWidth @@ -141,6 +149,7 @@ export function ConversationWidthControls({ container, phase }: ConversationWidt const preference = readWidthPreference() if (preference === null) target.style.removeProperty('--dsh-chat-user-width') else target.style.setProperty('--dsh-chat-user-width', `${resolveContentWidth(column, preference)}px`) + report.current((column - resolveContentWidth(column, preference)) / 2) }, []) useLayoutEffect(() => { @@ -148,7 +157,10 @@ export function ConversationWidthControls({ container, phase }: ConversationWidt const observer = new ResizeObserver(() => { publishWidths(container) }) observer.observe(container) publishWidths(container) - return () => { observer.disconnect() } + return () => { + observer.disconnect() + report.current(0) + } }, [container, publishWidths]) const onStart = useCallback((): number => { @@ -158,7 +170,10 @@ export function ConversationWidthControls({ container, phase }: ConversationWidt const onDrag = useCallback((width: number): void => { if (container === null) return const target = container.parentElement ?? container - target.style.setProperty('--dsh-chat-user-width', `${resolveContentWidth(container.offsetWidth, width)}px`) + const column = container.offsetWidth + const content = resolveContentWidth(column, width) + target.style.setProperty('--dsh-chat-user-width', `${content}px`) + report.current((column - content) / 2) }, [container]) const onCommit = useCallback((width: number): void => { if (container === null) return diff --git a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx index 2a099a7d7b..c82b03cb77 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -147,6 +147,8 @@ function mount( entryActions?: boolean /** Isolate header capability checks from the composer's required layout observers. */ headerOnly?: boolean + /** Render the content Factory as another presentation host would. */ + contentVariant?: 'embedded' } = {}, ) { const sessionId = 'sessionId' in options ? options.sessionId : SID @@ -204,6 +206,8 @@ function mount( const frameOwners: HeroFrameOwnerProps[] = [] let actionsOwner: ConversationViewActionsOwnerProps | undefined const setPinned = vi.fn<(id: string, pinned: boolean) => void>() + /** End gutters the main width controls reported, in order. */ + const gutters: number[] = [] const renderSlot = ((key: string, owner: object, opts?: { only?: string; fallback?: ReactNode; children?: ReactNode }) => { slotCalls.push(key) if (key === 'conversation.input.model' || key === 'conversation.input.plan') { @@ -376,6 +380,7 @@ function mount( renderSlotChain, renderFactorySlot, selectWorkspace: retargetWorkspace, + reportEndGutter: (gutter) => { gutters.push(gutter) }, t, } const useFactorySlot = ((name: string, fallback: (props: never) => ReactNode) => ( @@ -383,7 +388,11 @@ function mount( )) as ConversationContentProps['useFactorySlot'] return ( - + ) }) as ConversationSlotProps['renderFactorySlot'] @@ -407,7 +416,7 @@ function mount( const props: ConversationSlotProps = { ...runtimeProps, renderSlot, renderFactorySlot } const view = render() return { - view, store, wiring, sink, retargetWorkspace, session, conversation, slotCalls, headerFactory, lineageOwners, seatOwners, open, + view, store, wiring, sink, retargetWorkspace, session, conversation, slotCalls, headerFactory, lineageOwners, seatOwners, open, gutters, pickerOwner: () => pickerOwner, frameOwner: () => frameOwners.at(-1), setPinned, @@ -1074,4 +1083,53 @@ describe('ConversationRoot resident composer', () => { const b = mount(sessionSnapshotOf({ blank: true })) expect(b.view.container.querySelector('[data-width-handle]')).toBeNull() }) + + it('reports the end gutter after each measurement and drag frame, and zero on unmount', () => { + const b = mount(sessionSnapshotOf()) + const content = b.view.container.querySelector('[data-conversation-content]') as HTMLElement + Object.defineProperty(content, 'offsetWidth', { value: 1600, configurable: true }) + act(() => { fireResize(content) }) + // Adaptive width min(1600 × 0.64, 920) = 920 leaves (1600 − 920) / 2. + expect(b.gutters.at(-1)).toBe(340) + const handle = b.view.container.querySelector('[data-width-handle="right"]') as HTMLElement + const names = ['setPointerCapture', 'releasePointerCapture', 'hasPointerCapture'] as const + const originals = names.map(name => [name, Object.getOwnPropertyDescriptor(Element.prototype, name)] as const) + const captured = new Set() + Element.prototype.setPointerCapture = function () { captured.add(this) } + Element.prototype.releasePointerCapture = function () { captured.delete(this) } + Element.prototype.hasPointerCapture = function () { return captured.has(this) } + try { + fireEvent.pointerDown(handle, { pointerId: 1, clientX: 800, clientY: 300 }) + fireEvent.pointerMove(handle, { pointerId: 1, clientX: 825, clientY: 300 }) + fireEvent.pointerUp(handle, { pointerId: 1, clientX: 825, clientY: 300 }) + // The dragged width 970 leaves (1600 − 970) / 2. + expect(b.gutters.at(-1)).toBe(315) + } finally { + for (const [name, descriptor] of originals) { + if (descriptor === undefined) Reflect.deleteProperty(Element.prototype, name) + else Object.defineProperty(Element.prototype, name, descriptor) + } + } + b.view.unmount() + expect(b.gutters.at(-1)).toBe(0) + }) + + it('renders the Session panel seat only for the main occurrence of an active Session', () => { + expect(mount(sessionSnapshotOf()).slotCalls).toContain('conversation.session.panel') + cleanup() + expect(mount(sessionSnapshotOf({ blank: true })).slotCalls).not.toContain('conversation.session.panel') + cleanup() + expect(mount(sessionSnapshotOf(), undefined, undefined, { contentVariant: 'embedded' }).slotCalls) + .not.toContain('conversation.session.panel') + }) + + it('publishes the composer stack measurements on the content body', () => { + const b = mount(sessionSnapshotOf()) + const content = b.view.container.querySelector('[data-conversation-content]') as HTMLElement + const seat = content.querySelector('[data-composer-seat]') as HTMLElement + Object.defineProperty(seat, 'offsetHeight', { value: 140, configurable: true }) + act(() => { fireResize(seat) }) + expect(content.style.getPropertyValue('--dsh-composer-height')).toBe('140px') + expect(content.style.getPropertyValue('--dsh-conversation-viewport-height')).toBe('0px') + }) }) diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 57651951e1..3bc5cc09e4 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -18,8 +18,8 @@ en: ead6be55c7c9d7cf zh: 125ad36db7328551 /deepseek-ai-dsh-client-ui-primitives/use-this-package/component-catalog: - en: ae85dcbb25303332 - zh: 471224ebad67df91 + en: 593d2716ae6b17a6 + zh: ff2605eb22969aa6 /deepseek-ai-dsh-client-ui-primitives/use-this-package/controls-and-icons: en: 2fc65b908307b52e zh: e5c1181ecd2da6e5 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index aa4fa2d978..d8be002218 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -55,6 +55,7 @@ Check this table before writing a control in a feature package. A plugin cannot | `SegmentedTabs` | Controlled equal-width tabs with a sliding indicator and Left/Right, Home, and End navigation. The caller supplies labels, tab/panel ids, and panel content. Default `size="md"` is 42px tall with a 4px inset; `size="sm"` is 34px tall with a 2px inset. | | `Tag` | Read-only capsule badge; `tone` selects one of eight palettes. | | `PathLabel` | Single-line file path with subdued directories, a primary filename, and the full path on hover. Fitting paths align left; clipped paths preserve their suffix with a left-edge fade that updates on path and size changes. | +| `PanelRow` | One fact row of a summary panel: a 16px decorative icon, single-line content that clips with an ellipsis, and an optional trailing value or control. The icon inherits the row ink. `onActivate` turns the icon and content into one button with hover and pressed fills while the trailing area stays outside it; other attributes, such as context-menu trigger props, reach the outer element. | | `StateDot` | Solid green `done`, amber `warning`, red `error`, and neutral-grey `idle` marks in a 10px slot, plus a tertiary-grey 14px rotating `ongoing` loader whose animations pin to document time zero on mount and on every animation restart, such as a list reorder, so every visible loader rotates in phase. `aria-hidden`, so the render site owns the name. `appearance="step"` shows a filled check for completion and a hollow pending circle. | | `ConnectionIndicator` | Inline connection-recovery control across outage, retry, and recovered states. | | `DisclosureRow` | 24px compact disclosure that lays title and content side by side. The header supplies tertiary at rest and secondary on hover; text and icons inherit it regardless of expandability or open state unless the caller supplies a feature-specific override. Semantic status colors remain explicit. Collapsed rows preview a down chevron on hover, and expanded rows keep an up chevron visible. `headerAccessory` places an independent action outside the disclosure target and shimmer; with an accessory, the title row shrinks to its content width. Memoized with shallow prop comparison; keep callbacks and React-node props stable when their content is unchanged. | diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 1eeebf6dac..d29c5816e8 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -55,6 +55,7 @@ kind: "package-library" | `SegmentedTabs` | 受控的等宽分段标签,支持滑动指示条及左/右方向键、Home、End 导航。调用方提供文案、标签与面板 id,以及面板内容。默认 `size="md"` 总高 42px、内边距 4px;`size="sm"` 总高 34px、内边距 2px。 | | `Tag` | 只读胶囊徽章;`tone` 选择八种配色之一。 | | `PathLabel` | 单行文件路径:目录使用弱化颜色,文件名使用主色,悬停可查看完整路径。空间足够时靠左显示;溢出时保留尾部并在左侧渐隐,路径或尺寸变化时更新。 | +| `PanelRow` | 摘要面板中的一行事实:16px 装饰图标、单行内容(溢出时以省略号截断)以及可选的尾部数值或控件。图标沿用行文字颜色。传入 `onActivate` 时,图标与内容成为同一个按钮,带悬停与按下填充,尾部区域留在按钮之外;其余属性(例如右键菜单触发属性)落在外层元素上。 | | `StateDot` | 10px 槽内的绿色 `done`、琥珀色 `warning`、红色 `error`、中性灰色 `idle` 圆点,以及 tertiary 灰色 14px 旋转 `ongoing` loading,其动画在挂载时以及每次动画重启(如列表重排)时固定到文档时间零点,所以所有可见 loading 同相旋转。它是 `aria-hidden` 的,名称由渲染点提供。 `appearance="step"` 以实心勾表示完成、空心圆表示等待。 | | `ConnectionIndicator` | 行内连接恢复控件,覆盖断线、重试与已恢复三种状态。 | | `DisclosureRow` | 24px 紧凑折叠行,标题与内容左右排列。标题行默认使用 tertiary,悬停时使用 secondary;文字与图标继承该颜色,不受能否展开及开合状态影响,调用方可提供功能专属覆盖。语义状态色保持显式指定。收起时悬停预览向下箭头,展开后持续显示向上箭头。`headerAccessory` 将独立操作放在折叠触发区域和流光之外;有此操作时,标题行收窄到内容宽度。使用浅层 prop 比较进行 memo;内容未变时,保持回调与 React 节点 prop 的引用稳定。 | diff --git a/packages/client/ui-primitives/src/PanelRow.module.css b/packages/client/ui-primitives/src/PanelRow.module.css new file mode 100644 index 0000000000..4a6c786fd8 --- /dev/null +++ b/packages/client/ui-primitives/src/PanelRow.module.css @@ -0,0 +1,78 @@ +/* One summary-panel fact: [16px icon] gap 8 [content 13/28] [trailing]. + The icon inherits the row ink so a fact and its glyph share one foreground. */ + +.row { + display: flex; + align-items: center; + gap: 4px; + min-width: 0; + color: var(--dsw-alias-label-primary); + font: var(--dsw-font-xs-13); +} + +.body { + display: flex; + flex: 1 1 auto; + align-items: center; + gap: 8px; + box-sizing: border-box; + min-width: 0; + height: 28px; + padding: 0 6px; + border-radius: var(--dsw-radius-sm); +} + +.action { + margin: 0; + border: 0; + color: inherit; + background: transparent; + font: inherit; + text-align: start; + cursor: pointer; +} + +@media (hover: hover) { + .action:hover { + background: var(--dsw-alias-interactive-bg-hover); + } +} + +.action:active { + background: var(--dsw-alias-interactive-bg-active); +} + +.action:focus-visible { + outline-style: solid; + outline-offset: -2px; +} + +.icon { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + width: 16px; + height: 16px; +} + +.icon svg { + width: 16px; + height: 16px; +} + +.content { + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.trailing { + display: inline-flex; + flex: none; + align-items: center; + gap: 4px; + color: var(--dsw-alias-label-tertiary); +} diff --git a/packages/client/ui-primitives/src/PanelRow.tsx b/packages/client/ui-primitives/src/PanelRow.tsx new file mode 100644 index 0000000000..a93fb95bf4 --- /dev/null +++ b/packages/client/ui-primitives/src/PanelRow.tsx @@ -0,0 +1,40 @@ +// PanelRow: one icon-led fact row of a summary panel, shared by every +// contributor so rows from different packages keep one geometry. + +import type { HTMLAttributes, ReactNode } from 'react' +import clsx from 'clsx' +import css from './PanelRow.module.css' + +/** Props of one summary-panel row. */ +export interface PanelRowProps extends Omit, 'children' | 'onClick'> { + /** Leading 16px glyph; decorative, so the row text carries the meaning. */ + readonly icon: ReactNode + /** Primary single-line content; overflow clips with an ellipsis. */ + readonly children: ReactNode + /** Optional trailing value or control, laid out after the content without shrinking. */ + readonly trailing?: ReactNode + /** Make the icon and content one button with this action; the trailing area stays outside it. */ + readonly onActivate?: (() => void) | undefined +} + +/** + * Render one summary-panel row: icon, single-line content, and an optional trailing area. + * @param props - row content, the optional action, and attributes for the outer element. + * @returns the row element. + */ +export function PanelRow({ icon, children, trailing, onActivate, className, ...attributes }: PanelRowProps) { + const body = ( + <> + + {children} + + ) + return ( +
+ {onActivate === undefined + ? {body} + : } + {trailing !== undefined && {trailing}} +
+ ) +} diff --git a/packages/client/ui-primitives/src/index.ts b/packages/client/ui-primitives/src/index.ts index 4fb059f603..8843254144 100644 --- a/packages/client/ui-primitives/src/index.ts +++ b/packages/client/ui-primitives/src/index.ts @@ -26,6 +26,8 @@ export type { SegmentedTab } from './SegmentedTabs.tsx' export { Tag } from './Tag.tsx' export type { TagTone } from './Tag.tsx' export { PathLabel } from './PathLabel.tsx' +export { PanelRow } from './PanelRow.tsx' +export type { PanelRowProps } from './PanelRow.tsx' export { Switch } from './Switch.tsx' export { SegmentedControl } from './SegmentedControl.tsx' export type { SegmentedControlOption } from './SegmentedControl.tsx' diff --git a/packages/client/ui-primitives/tests/panel-row.client.spec.tsx b/packages/client/ui-primitives/tests/panel-row.client.spec.tsx new file mode 100644 index 0000000000..7a7b28f497 --- /dev/null +++ b/packages/client/ui-primitives/tests/panel-row.client.spec.tsx @@ -0,0 +1,41 @@ +// @vitest-environment jsdom +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { PanelRow } from '@deepseek-ai/dsh-client-ui-primitives' + +afterEach(cleanup) + +describe('PanelRow', () => { + it('renders a static fact with a decorative icon and no button', () => { + const view = render(}>deepseek-harness) + expect(screen.getByText('deepseek-harness')).toBeTruthy() + expect(screen.queryByRole('button')).toBeNull() + expect(screen.getByTestId('glyph').parentElement?.getAttribute('aria-hidden')).toBe('true') + expect(view.container.querySelector('[data-panel-row]')?.children).toHaveLength(1) + }) + + it('makes the icon and content one button while the trailing control stays outside it', () => { + const onActivate = vi.fn() + const onTrailing = vi.fn() + render( + } onActivate={onActivate} trailing={}> + Local changes + , + ) + fireEvent.click(screen.getByRole('button', { name: 'Local changes' })) + expect(onActivate).toHaveBeenCalledTimes(1) + fireEvent.click(screen.getByRole('button', { name: 'More' })) + expect(onTrailing).toHaveBeenCalledTimes(1) + expect(onActivate).toHaveBeenCalledTimes(1) + }) + + it('forwards attributes such as context-menu handlers to the outer element', () => { + const onContextMenu = vi.fn() + const view = render(} className="placed" onContextMenu={onContextMenu} tabIndex={0}>Row) + const row = view.container.querySelector('[data-panel-row]') as HTMLElement + expect(row.className).toContain('placed') + expect(row.tabIndex).toBe(0) + fireEvent.contextMenu(row) + expect(onContextMenu).toHaveBeenCalledTimes(1) + }) +}) diff --git a/packages/client/ui-session-panel/README.i18n.yaml b/packages/client/ui-session-panel/README.i18n.yaml new file mode 100644 index 0000000000..c93e04fcc3 --- /dev/null +++ b/packages/client/ui-session-panel/README.i18n.yaml @@ -0,0 +1,43 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/client/ui-session-panel/README.md +/: + en: b40a112d76d02bc9 + zh: 1c004debcd32eeea +/deepseek-ai-dsh-client-ui-session-panel: + en: aff5b9d70836e810 + zh: 2cb8c75d3c82fba9 +/deepseek-ai-dsh-client-ui-session-panel/summary: + en: d80ba3f8b8bf0f6c + zh: eb9b13bbfc712eba +/deepseek-ai-dsh-client-ui-session-panel/table-of-contents: + en: d152484eb41ac6b4 + zh: 09388d293f9be9cb +/deepseek-ai-dsh-client-ui-session-panel/use-this-package: + en: d7818d67e981be3c + zh: c7c0c704d5ef8b34 +/deepseek-ai-dsh-client-ui-session-panel/use-this-package/docking-and-the-overlay: + en: 1d99ccdba0457d10 + zh: 81833d87548d3225 +/deepseek-ai-dsh-client-ui-session-panel/use-this-package/contribute-a-section: + en: 3e9463ce11beff16 + zh: d10d474c06afa3ca +/deepseek-ai-dsh-client-ui-session-panel/understand-the-implementation: + en: e59cf3dc6b08e893 + zh: 33548291a59090c2 +/deepseek-ai-dsh-client-ui-session-panel/further-exploration: + en: 4ae4610263ad0c16 + zh: df16dc60d5af7740 +/deepseek-ai-dsh-client-ui-session-panel/model-experience: + en: 7e8bbe318a76fd54 + zh: c60e87da2a37642a +/deepseek-ai-dsh-client-ui-session-panel/model-experience/kv-cache-effect: + en: 47f982e326fe77fd + zh: 275b2ef7eec3ab19 +/deepseek-ai-dsh-client-ui-session-panel/known-limitations-and-deferred-work: + en: a0a860bdaf255e6a + zh: f46448570dcaec2c +/deepseek-ai-dsh-client-ui-session-panel/known-limitations-and-deferred-work/dev-note: + en: e67f633dc6fe7773 + zh: b532016223ceceef diff --git a/packages/client/ui-session-panel/README.md b/packages/client/ui-session-panel/README.md new file mode 100644 index 0000000000..b8d1ee4f87 --- /dev/null +++ b/packages/client/ui-session-panel/README.md @@ -0,0 +1,109 @@ +--- +description: "The Session panel: a header toggle and a floating panel over the main Conversation body whose sections other plugins register, with the built-in Environment section." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-session-panel + +English | [中文](README.zh.md) + +## Summary + +`dsh-client-ui-session-panel` adds a Session header toggle that shows or hides a floating panel of facts about the current Session. The panel docks in the main Conversation body's end gutter when the gutter can hold it, and otherwise opens over the transcript on request. It draws section titles and leaves section content to the plugins that register sections; it ships the Environment section with the project directory row. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +The `@deepseek-ai/dsh-web-app` bundle loads this package by default. The toggle is the first Session header utility, before change requests, sharing, and the schedule catalog. It is an icon button with the panel name and its indicators as its accessible name, a tooltip that says whether a press shows or hides the panel, and `aria-expanded` for whether the panel shows. + +### Docking and the overlay + +The panel docks while the gutter between the transcript column and the body's end edge is at least 344px: 48px clear of the column and its width handle, the panel's 280px minimum width, and a 16px edge margin. Docked, it is 280–340px wide, starts 12px below the header, and scrolls inside itself. Pressing the toggle then flips one docking preference that every Session shares and that persists in `localStorage` under `dsh.sessionPanel.pinned`; the panel docks by default. + +A narrower gutter hides the docked panel, so it never covers the transcript. This includes a narrow window, an expanded right sidebar, a dragged-wide transcript column, and every View other than Chat, because those Views fill the body. Pressing the toggle then opens the panel over the transcript with the prominent elevation, above the composer stack and not covering it. The overlay closes from the toggle, on Escape, and on a pointer press outside the panel, the toggle, and any open menu, such as a row's context menu; Escape returns focus to the toggle when focus was inside the panel, and a modal above the page keeps Escape. Closing it does not change the docking preference. At most one Session's overlay is open, and docking from a wide gutter closes it. + + +### Contribute a section + +A section is one `conversation.session.panel.section` list registration: `id` addresses it, `order` sorts it ascending, and the required `label` is its title, which the panel draws in the active locale. The section component receives `presentation` (`docked` or `overlay`) and `dismissOverlay()` as owner props; it renders its body and renders nothing when it has nothing to show, which hides its title too. Register trailing title controls, such as a count or a refresh button, in the keyed `conversation.session.panel.section.actions` slot under the section's `id`. A section without a label is reported to the console and not shown. + +Plugins share a title by registering rows in a section owner's row slot. The built-in Environment section (`id: 'environment'`, `order: 0`) declares `conversation.session.panel.environment.row`; its `project` row (`order: 0`) shows the directory of the Workspace that lists the Session, or the directory the Session was created in, with the Host home abbreviated to `~`. Right-clicking the row or pressing its More button opens the shared `directory` context menu. A plugin that owns a shared section declares its own row slot the same way. + +Marks that must stay visible while the panel is hidden, such as an attention dot, go in the `conversation.session.panel.indicator` list. Each occupant includes text that names it, which becomes part of the toggle's accessible name. + +Summary rows from every package use the `PanelRow` primitive, so icon, text, and trailing areas line up across sections. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +The toggle and the panel are separate Slot entries that share one plugin-owned visibility source: the persisted docking preference and the Session whose overlay is open. Both read the Session's main body geometry from `ctx.uiConversation.layouts`, which the Conversation width controls write from their existing measurement, and decide the presentation with the same pure function, so the toggle's state never disagrees with the panel. The panel renders inside the main Conversation body, which owns its positioning context, the transcript axis, and the composer stack height. + +The panel projects the section list's live registrations (`entriesOfSlot`, so a higher-priority registration with the same `id` replaces a shipped section) into `{ id, label }` rows, recomputed only when the ledger version or the locale revision changes. It renders each section through `renderSlot(..., { only: id })` inside its own title and body; a CSS `:has()` rule hides a section whose body outlet stayed empty, including a shared section whose row outlet stayed empty. + +| File | Role | +|---|---| +| [`src/client/index.ts`](src/client/index.ts) | Dictionaries, the toggle, the panel, the Environment section, and the project row | +| [`src/client/slots.ts`](src/client/slots.ts) | Slot declarations and component props | +| [`src/client/visibility.ts`](src/client/visibility.ts) | Docking threshold, presentation, and the shared visibility state | +| [`src/client/sections.ts`](src/client/sections.ts) | Section roster projection | +| [`src/client/SessionPanel.tsx`](src/client/SessionPanel.tsx) | The panel, its section titles, and Escape handling | +| [`src/client/SessionPanelToggle.tsx`](src/client/SessionPanelToggle.tsx) | The header toggle and its indicators | +| [`src/client/ProjectRow.tsx`](src/client/ProjectRow.tsx) | The project directory row | + +
+ +----- + + +## Further Exploration + +- [Web Client Slots](../../../docs/subsystems/slots.md) — list, keyed, and owner-prop semantics the sections rely on. +- [`dsh-client-ui-conversation`](../ui-conversation/README.md) — the Session header utilities, the panel seat, and the main body geometry. +- [`dsh-client-ui-primitives`](../ui-primitives/README.md#component-catalog) — `PanelRow` and `PathLabel`. + +----- + + +## Model Experience + +None, as this package renders facts the Client already holds for a human and touches no prompt, message, schema, stream, or tool result. + +#### KV Cache effect + +None; the package never assembles or sends provider requests. + +## Known Limitations and Deferred Work + + + +These limits define current package constraints, not a task backlog. + +- **Laptop widths overlay rather than dock** — with the default transcript width the body must be at least about 1608px wide to dock; narrower bodies use the overlay. Docking by moving the transcript column aside is a separate layout decision. +- **No execution environment row** — the Client has no per-Session fact for the local machine, an SSH host, or the sandbox mode, so the Environment section names only the project directory. +- **No section customization** — every live section shows; hiding or reordering sections from the panel is not offered. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/client/ui-session-panel/README.zh.md b/packages/client/ui-session-panel/README.zh.md new file mode 100644 index 0000000000..b2e8b394bf --- /dev/null +++ b/packages/client/ui-session-panel/README.zh.md @@ -0,0 +1,109 @@ +--- +description: "会话面板:会话标题栏开关与主对话区上方的悬浮面板,分栏由其他插件注册,并内置「环境」分栏。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-session-panel + +[English](README.md) | 中文 + +## 概述 + +`dsh-client-ui-session-panel` 在会话标题栏加一个开关,用来显示或隐藏一块汇总当前会话信息的悬浮面板。主对话区末端留白放得下面板时,面板停靠在留白里;放不下时,按需浮在对话正文上方。面板只绘制分栏标题,分栏内容交给注册分栏的插件;本包内置「环境」分栏及其项目目录行。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +`@deepseek-ai/dsh-web-app` 套件默认加载本包。开关是会话标题栏的第一个工具按钮,位于变更请求、共享和计划任务目录之前。它是图标按钮:无障碍名称由面板名称和其角标组成,提示文字说明按下后是显示还是隐藏面板,`aria-expanded` 表示面板当前是否显示。 + +### 停靠与浮层 + +正文列到对话区末端边缘的留白不少于 344px 时,面板停靠:与正文列及其宽度手柄保持 48px 间距,面板最小宽度 280px,外加 16px 边距。停靠时面板宽 280–340px,位于标题栏下方 12px,内容在面板内滚动。此时按开关会切换所有会话共用的停靠偏好,偏好存放在 `localStorage` 的 `dsh.sessionPanel.pinned` 中;默认停靠。 + +留白更窄时隐藏停靠面板,保证不遮挡正文。窗口变窄、展开右侧栏、把正文列拖宽,以及切换到 Chat 以外的视图(这些视图占满对话区)都会如此。此时按开关,面板以更强的阴影浮在正文上方,位于输入框区域之上,且不遮挡输入框。浮层可以用开关关闭,也会在按 Esc 时,或在面板、开关和任何已打开的菜单(例如行的上下文菜单)之外按下指针时关闭;焦点原本在面板内时,按 Esc 后焦点回到开关,页面上方有模态框时 Esc 归模态框处理。关闭浮层不改变停靠偏好。同一时间最多一个会话的浮层处于打开状态,在宽留白下切换停靠也会关闭它。 + + +### 贡献分栏 + +一个分栏是 `conversation.session.panel.section` 列表里的一次注册:`id` 用于寻址,`order` 升序排列,必填的 `label` 是标题,面板按当前语言绘制。分栏组件通过 owner props 收到 `presentation`(`docked` 或 `overlay`)和 `dismissOverlay()`;它负责渲染正文,没有内容时什么都不渲染,标题随之隐藏。标题尾部的控件(例如计数或刷新按钮)注册到以分栏 `id` 为键的 keyed slot `conversation.session.panel.section.actions`。缺少 label 的分栏会报告到控制台,并且不显示。 + +多个插件共用一个标题时,把行注册到分栏拥有者的行 slot 中。内置「环境」分栏(`id: 'environment'`,`order: 0`)声明 `conversation.session.panel.environment.row`;其 `project` 行(`order: 0`)显示列出本会话的工作区目录,或会话创建时所在的目录,宿主家目录缩写为 `~`。右键该行或点其「更多」按钮会打开共享的 `directory` 上下文菜单。拥有共享分栏的插件用同样方式声明自己的行 slot。 + +面板隐藏时也要可见的标记(例如需要处理的红点)放进 `conversation.session.panel.indicator` 列表。每个占位都带有说明自身的文字,这些文字会成为开关无障碍名称的一部分。 + +各包的摘要行都使用 `PanelRow` 原语,使不同分栏的图标、文字与尾部区域对齐。 + +----- + + +## 理解实现 + +
+实现内幕——点击展开 + +开关与面板是两个独立的 Slot 条目,共享一个插件持有的可见性 source:持久化的停靠偏好,以及打开了浮层的会话。两者都从 `ctx.uiConversation.layouts` 读取该会话的主对话区几何信息(由 Conversation 宽度控件在已有的测量中写入),并用同一个纯函数决定呈现方式,因此开关状态始终与面板一致。面板渲染在主对话区内部,对话区持有其定位上下文、正文轴线和输入框区域高度。 + +面板把分栏列表的实时注册(`entriesOfSlot`,因此同 `id` 且优先级更高的注册会替换已发布的分栏)投影为 `{ id, label }` 行,只在台账版本或语言版本变化时重新计算。它在各分栏自己的标题和正文容器里用 `renderSlot(..., { only: id })` 渲染内容;CSS `:has()` 规则隐藏正文出口为空的分栏,也包括行出口为空的共享分栏。 + +| 文件 | 作用 | +|---|---| +| [`src/client/index.ts`](src/client/index.ts) | 字典、开关、面板、「环境」分栏与项目行 | +| [`src/client/slots.ts`](src/client/slots.ts) | Slot 声明与组件 props | +| [`src/client/visibility.ts`](src/client/visibility.ts) | 停靠阈值、呈现方式与共享可见性状态 | +| [`src/client/sections.ts`](src/client/sections.ts) | 分栏名单投影 | +| [`src/client/SessionPanel.tsx`](src/client/SessionPanel.tsx) | 面板、分栏标题与 Esc 处理 | +| [`src/client/SessionPanelToggle.tsx`](src/client/SessionPanelToggle.tsx) | 标题栏开关及其角标 | +| [`src/client/ProjectRow.tsx`](src/client/ProjectRow.tsx) | 项目目录行 | + +
+ +----- + + +## 进一步探索 + +- [Web Client Slots](../../../docs/subsystems/slots.zh.md)——分栏依赖的 list、keyed 与 owner props 语义。 +- [`dsh-client-ui-conversation`](../ui-conversation/README.zh.md)——会话标题栏工具区、面板落位与主对话区几何信息。 +- [`dsh-client-ui-primitives`](../ui-primitives/README.zh.md#component-catalog)——`PanelRow` 与 `PathLabel`。 + +----- + + +## 模型体验 + +无。本包为用户展示客户端已有的信息,不涉及任何 prompt、消息、schema、流或工具结果。 + +#### KV 缓存影响 + +无;本包从不组装或发送模型请求。 + +## 已知限制与延期工作 + + + +以下限制定义的是当前包的约束,而非任务待办清单。 + +- **笔记本宽度下使用浮层而非停靠**——在默认正文宽度下,对话区宽度需约 1608px 以上才能停靠;更窄时使用浮层。通过把正文列移开来停靠属于另一项布局决策。 +- **没有运行环境行**——客户端没有区分本机、SSH 主机或沙箱模式的会话级信息,因此「环境」分栏只显示项目目录。 +- **不能自定义分栏**——所有有内容的分栏都会显示;面板不提供隐藏或重新排序分栏的功能。 + + +### 开发备注 + +
+维护者工作语境——点击展开 + +无。 + +
diff --git a/packages/client/ui-session-panel/locale/de.json b/packages/client/ui-session-panel/locale/de.json new file mode 100644 index 0000000000..251422de2d --- /dev/null +++ b/packages/client/ui-session-panel/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Sitzungsbereich", + "description": "Ein schwebender Bereich, der sich über die Sitzungskopfzeile öffnet und Informationen zur aktuellen Sitzung bündelt, etwa ihr Projektverzeichnis." + } +} diff --git a/packages/client/ui-session-panel/locale/en.json b/packages/client/ui-session-panel/locale/en.json new file mode 100644 index 0000000000..b461d8432e --- /dev/null +++ b/packages/client/ui-session-panel/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Session panel", + "description": "A floating panel opened from the Session header that gathers facts about the current Session, such as its project directory." + } +} diff --git a/packages/client/ui-session-panel/locale/es.json b/packages/client/ui-session-panel/locale/es.json new file mode 100644 index 0000000000..ef7f34e387 --- /dev/null +++ b/packages/client/ui-session-panel/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Panel de la sesión", + "description": "Un panel flotante que se abre desde el encabezado de la sesión y reúne información de la sesión actual, como su directorio de proyecto." + } +} diff --git a/packages/client/ui-session-panel/locale/fr.json b/packages/client/ui-session-panel/locale/fr.json new file mode 100644 index 0000000000..289ee3e312 --- /dev/null +++ b/packages/client/ui-session-panel/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Panneau de session", + "description": "Un panneau flottant ouvert depuis l'en-tête de la session qui regroupe les informations de la session en cours, comme son dossier de projet." + } +} diff --git a/packages/client/ui-session-panel/locale/ja.json b/packages/client/ui-session-panel/locale/ja.json new file mode 100644 index 0000000000..deb479ceca --- /dev/null +++ b/packages/client/ui-session-panel/locale/ja.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "セッションパネル", + "description": "セッションのヘッダーから開くフローティングパネルで、プロジェクトディレクトリなど現在のセッションに関する情報をまとめて表示します。" + } +} diff --git a/packages/client/ui-session-panel/locale/pt.json b/packages/client/ui-session-panel/locale/pt.json new file mode 100644 index 0000000000..b5e3f34378 --- /dev/null +++ b/packages/client/ui-session-panel/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Painel da sessão", + "description": "Um painel flutuante aberto pelo cabeçalho da sessão que reúne informações da sessão atual, como a pasta do projeto." + } +} diff --git a/packages/client/ui-session-panel/locale/ru.json b/packages/client/ui-session-panel/locale/ru.json new file mode 100644 index 0000000000..7ac5e13e5e --- /dev/null +++ b/packages/client/ui-session-panel/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Панель сеанса", + "description": "Плавающая панель, которая открывается из заголовка сеанса и собирает сведения о текущем сеансе, например его каталог проекта." + } +} diff --git a/packages/client/ui-session-panel/locale/zh.json b/packages/client/ui-session-panel/locale/zh.json new file mode 100644 index 0000000000..f7fb68e766 --- /dev/null +++ b/packages/client/ui-session-panel/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "会话面板", + "description": "在会话标题栏打开悬浮面板,集中展示项目目录等与当前会话相关的信息。" + } +} diff --git a/packages/client/ui-session-panel/package.json b/packages/client/ui-session-panel/package.json new file mode 100644 index 0000000000..44aa1ebc95 --- /dev/null +++ b/packages/client/ui-session-panel/package.json @@ -0,0 +1,78 @@ +{ + "name": "@deepseek-ai/dsh-client-ui-session-panel", + "description": "Floating Session panel opened from the Session header, composed of sections that plugins register", + "version": "0.2.2-rc.1", + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./client": { + "types": "./lib/types/client/index.d.ts", + "default": "./lib/client.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" + }, + "scripts": { + "bundle": "tsdown", + "watch": "tsdown --watch" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/client/ui-session-panel" + }, + "publishConfig": { + "access": "public" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-api-remotes": "workspace:*", + "@deepseek-ai/dsh-api-session-controller": "workspace:*", + "@deepseek-ai/dsh-api-workspace-controller": "workspace:*", + "@deepseek-ai/dsh-client-locale": "workspace:*", + "@deepseek-ai/dsh-client-store": "workspace:*", + "@deepseek-ai/dsh-client-test-runtime": "workspace:*", + "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*", + "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", + "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", + "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", + "@deepseek-ai/dsh-client-ui-session": "workspace:*", + "@deepseek-ai/dsh-client-ui-slots": "workspace:*", + "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-util-workspace-path": "workspace:*", + "@deepseek-ai/dsh-workspace": "workspace:*", + "@testing-library/react": "^16.3.3", + "clsx": "^2.0.0", + "react": "^18.2.0", + "react-dom": "^18.2.0" + }, + "files": [ + "locale/*.json", + "lib/index.js", + "lib/client.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "src" + ], + "dsh": { + "client": { + "inject": [ + "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-client-ui-conversation", + "@deepseek-ai/dsh-client-ui-primitives" + ], + "platform": "web" + } + } +} diff --git a/packages/client/ui-session-panel/src/client/EnvironmentSection.tsx b/packages/client/ui-session-panel/src/client/EnvironmentSection.tsx new file mode 100644 index 0000000000..eeaa815bbf --- /dev/null +++ b/packages/client/ui-session-panel/src/client/EnvironmentSection.tsx @@ -0,0 +1,13 @@ +/** Built-in Environment section: one shared title over the rows other plugins register. */ +import type { ReactNode } from 'react' +import type { EnvironmentSectionProps } from './slots.ts' + +/** + * Render the Environment rows. The rows render straight into the section + * body, so a section without rows renders nothing and the panel hides it. + * @param props - the section's child renderer. + * @returns the row outlet. + */ +export function EnvironmentSection({ renderSlot }: EnvironmentSectionProps): ReactNode { + return renderSlot('conversation.session.panel.environment.row', {}) +} diff --git a/packages/client/ui-session-panel/src/client/ProjectRow.module.css b/packages/client/ui-session-panel/src/client/ProjectRow.module.css new file mode 100644 index 0000000000..e4561fd1da --- /dev/null +++ b/packages/client/ui-session-panel/src/client/ProjectRow.module.css @@ -0,0 +1,12 @@ +/* The More button appears on row hover or focus; without hover it stays visible. */ +@media (hover: hover) { + .row .more { + opacity: 0; + } + + .row:hover .more, + .row:focus-within .more, + .more[aria-expanded='true'] { + opacity: 1; + } +} diff --git a/packages/client/ui-session-panel/src/client/ProjectRow.tsx b/packages/client/ui-session-panel/src/client/ProjectRow.tsx new file mode 100644 index 0000000000..9381ce1945 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/ProjectRow.tsx @@ -0,0 +1,38 @@ +/** Environment row naming the Session's project directory. */ +import type { ReactNode } from 'react' +import { IconFolderCloseRegular, PanelRow, PathLabel } from '@deepseek-ai/dsh-client-ui-primitives' +import { abbreviateHomePath } from '@deepseek-ai/dsh-util-workspace-path' +import type { ProjectRowProps } from './slots.ts' +import css from './ProjectRow.module.css' + +/** + * Render the project directory: the Workspace that lists the Session, or the + * directory the Session was created in when no Workspace lists it. The row + * and its More button open the directory context menu. + * @param props - Session values, Workspace and Session list hooks, Host facts, menu bindings, and copy. + * @returns the row, or null before the Session's directory is known. + */ +export function ProjectRow({ + sessionId, useWorkspaces, useSessions, useHost, useContextMenu, renderFactorySlot, t, +}: ProjectRowProps): ReactNode { + const workspacePath = useWorkspaces(snapshot => snapshot.items.find(item => item.sessionIds.includes(sessionId))?.path) + const createdIn = useSessions(snapshot => snapshot.byId[sessionId]?.cwd) + const home = useHost(facts => facts.home) + const { getTriggerProps } = useContextMenu() + const path = workspacePath ?? createdIn + if (path === undefined) return null + const target = { kind: 'directory', value: { sessionId, path } } as const + return ( + } + trailing={renderFactorySlot('contextMenu.button', { + target, label: t('project.actions'), className: css.more, size: 'sm', + })} + data-session-panel-project="" + > + + + ) +} diff --git a/packages/client/ui-session-panel/src/client/SessionPanel.module.css b/packages/client/ui-session-panel/src/client/SessionPanel.module.css new file mode 100644 index 0000000000..f3bc08665e --- /dev/null +++ b/packages/client/ui-session-panel/src/client/SessionPanel.module.css @@ -0,0 +1,93 @@ +/* The panel floats over the main Conversation body (position: relative), + which defines the transcript axis --dsh-chat-content-width and publishes + the composer stack height --dsh-composer-height. */ +.panel { + position: absolute; + top: 12px; + right: 16px; + /* Above the turn rail (7), level with the back-to-bottom control (8), and + below the composer seat (9); the docked width keeps 48px clear of the + transcript column and its width handle. */ + z-index: 8; + box-sizing: border-box; + width: clamp(280px, calc((100% - var(--dsh-chat-content-width)) / 2 - 64px), 340px); + max-height: calc(100% - 24px); + overflow-y: auto; + overscroll-behavior: contain; + padding: 6px 8px; + border: 0; + border-radius: var(--dsw-radius-panel); + color: var(--dsw-alias-label-primary); + background: var(--dsw-alias-bg-layer-1); + box-shadow: var(--dsw-elevation-panel); + animation: dsh-session-panel-enter 120ms ease-out; +} + +/* Over the transcript the panel takes the prominent elevation and stops above + the composer stack, whose card it would otherwise cover. */ +.panel[data-session-panel='overlay'] { + right: 12px; + z-index: 10; + width: min(340px, calc(100% - 24px)); + max-height: calc(100% - var(--dsh-composer-height, 152px) - 24px); + box-shadow: var(--dsw-elevation-prominent); +} + +.section { + padding: 4px 0 6px; +} + +/* An empty body hides its section: a plain section renders into one outlet + anchor, and a shared section renders its own row outlet inside it. */ +.section:has(> .body > [data-slot]:empty), +.section:has(> .body > [data-slot] > [data-slot]:only-child:empty) { + display: none; +} + +.section:not(:has(> .body > [data-slot]:empty), :has(> .body > [data-slot] > [data-slot]:only-child:empty)) + ~ .section:not(:has(> .body > [data-slot]:empty), :has(> .body > [data-slot] > [data-slot]:only-child:empty)) { + margin-top: 2px; + padding-top: 8px; + border-top: 0.5px solid var(--dsw-alias-border-l2); +} + +.head { + display: flex; + align-items: center; + gap: 4px; + min-height: 24px; + padding: 0 6px; +} + +.title { + flex: 1 1 auto; + min-width: 0; + margin: 0; + overflow: hidden; + color: var(--dsw-alias-label-tertiary); + font: var(--dsw-font-xxs-12); + text-overflow: ellipsis; + white-space: nowrap; +} + +.actions { + display: inline-flex; + flex: none; + align-items: center; + gap: 2px; +} + +.actions:has(> [data-slot]:empty) { + display: none; +} + +@keyframes dsh-session-panel-enter { + from { opacity: 0; transform: translateY(-4px); } + to { opacity: 1; transform: translateY(0); } +} + +@media (prefers-reduced-motion: reduce) { + .panel { + animation: none; + } +} diff --git a/packages/client/ui-session-panel/src/client/SessionPanel.tsx b/packages/client/ui-session-panel/src/client/SessionPanel.tsx new file mode 100644 index 0000000000..ffe655bc7d --- /dev/null +++ b/packages/client/ui-session-panel/src/client/SessionPanel.tsx @@ -0,0 +1,93 @@ +/** Floating Session panel: section titles drawn from the section roster, bodies from the section slot. */ +import { useCallback, useEffect, useMemo, useRef, type ReactNode } from 'react' +import { isBehindModal } from '@deepseek-ai/dsh-client-ui-primitives' +import { panelElementId, toggleElementId } from './element-ids.ts' +import type { SessionPanelProps, SessionPanelSectionOwnerProps } from './slots.ts' +import { fitsLayout, presentationOf } from './visibility.ts' +import css from './SessionPanel.module.css' + +/** + * Close the overlay on Escape and on a pointerdown outside the panel. The + * toggle and open menus, such as a row's context menu, count as inside, and a + * modal above the page keeps Escape. Escape returns focus to the toggle when + * focus was inside the panel. + * @param panel - the overlay element. + * @param open - whether the overlay shows; false detaches the listeners. + * @param toggleId - id of the Session's toggle. + * @param close - closes the overlay. + */ +function useOverlayDismissal(panel: { readonly current: HTMLElement | null }, open: boolean, toggleId: string, close: () => void): void { + useEffect(() => { + if (!open) return + const inside = (target: EventTarget | null): boolean => target instanceof Element && ( + panel.current?.contains(target) === true + || document.getElementById(toggleId)?.contains(target) === true + || target.closest('[role="menu"]') !== null + ) + const onPointerDown = (event: PointerEvent): void => { + if (!inside(event.target)) close() + } + const onKeyDown = (event: KeyboardEvent): void => { + if (event.key !== 'Escape' || event.defaultPrevented || isBehindModal(panel.current)) return + event.preventDefault() + const focused = panel.current?.contains(document.activeElement) === true + close() + if (focused) document.getElementById(toggleId)?.focus() + } + document.addEventListener('pointerdown', onPointerDown) + document.addEventListener('keydown', onKeyDown) + return () => { + document.removeEventListener('pointerdown', onPointerDown) + document.removeEventListener('keydown', onKeyDown) + } + }, [panel, open, toggleId, close]) +} + +/** + * Render the panel while it docks or shows as an overlay. Each section keeps + * its title row and body; CSS hides a section whose body rendered nothing. + * The overlay closes on Escape and on an outside pointerdown. + * @param props - Session values, the main body layout, shared visibility, sections, and copy. + * @returns the panel, or null while it is hidden. + */ +export function SessionPanel({ + sessionId, useLayout, useVisibility, useSections, closeOverlay, renderSlot, t, +}: SessionPanelProps): ReactNode { + const fits = useLayout(fitsLayout) + const presentation = useVisibility(visibility => presentationOf(fits, visibility, sessionId)) + const sections = useSections(entries => entries) + const panel = useRef(null) + const dismissOverlay = useCallback(() => { closeOverlay(sessionId) }, [closeOverlay, sessionId]) + const owner = useMemo((): SessionPanelSectionOwnerProps | undefined => presentation === 'hidden' + ? undefined + : { presentation, dismissOverlay }, + [presentation, dismissOverlay]) + useOverlayDismissal(panel, presentation === 'overlay', toggleElementId(sessionId), dismissOverlay) + if (owner === undefined) return null + return ( + + ) +} diff --git a/packages/client/ui-session-panel/src/client/SessionPanelToggle.module.css b/packages/client/ui-session-panel/src/client/SessionPanelToggle.module.css new file mode 100644 index 0000000000..0b6b15562b --- /dev/null +++ b/packages/client/ui-session-panel/src/client/SessionPanelToggle.module.css @@ -0,0 +1,39 @@ +/* Icon-only header entry: the shared compact Button owns the radius, height, + and interaction fills, as for the header's other utilities. Indicators sit + at the glyph's top-right corner. */ +.trigger { + position: relative; + flex: none; + width: 28px; + padding: 0; + color: var(--dsw-alias-label-secondary); +} + +/* The panel shows; the expanded fill outranks the Button's hover fill. */ +.trigger[aria-expanded='true'] { + color: var(--dsw-alias-label-primary); + background: var(--dsw-alias-interactive-bg-active); +} + +@media (hover: hover) { + .trigger[aria-expanded='true']:hover:not(:disabled) { + color: var(--dsw-alias-label-primary); + background: var(--dsw-alias-interactive-bg-active); + } +} + +/* The name reaches assistive technology; the tooltip carries it visually. */ +.name { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} + +.trigger > :global([data-slot='conversation.session.panel.indicator']) > * { + position: absolute; + top: 6px; + right: 6px; +} diff --git a/packages/client/ui-session-panel/src/client/SessionPanelToggle.tsx b/packages/client/ui-session-panel/src/client/SessionPanelToggle.tsx new file mode 100644 index 0000000000..f99d9d487c --- /dev/null +++ b/packages/client/ui-session-panel/src/client/SessionPanelToggle.tsx @@ -0,0 +1,39 @@ +/** Session header entry that shows or hides the Session panel. */ +import type { ReactNode } from 'react' +import { Button, IconFlatListOutlineRegular, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' +import { panelElementId, toggleElementId } from './element-ids.ts' +import type { SessionPanelToggleProps } from './slots.ts' +import { fitsLayout, presentationOf } from './visibility.ts' +import css from './SessionPanelToggle.module.css' + +/** + * Render the toggle. Its accessible name is the panel name followed by the + * text of any indicator; the expanded state says whether the panel shows. + * @param props - Session values, the main body layout, shared visibility, the toggle action, and copy. + * @returns the header entry. + */ +export function SessionPanelToggle({ + sessionId, useLayout, useVisibility, toggle, renderSlot, t, +}: SessionPanelToggleProps): ReactNode { + const fits = useLayout(fitsLayout) + const open = useVisibility(visibility => presentationOf(fits, visibility, sessionId) !== 'hidden') + return ( + + + + ) +} diff --git a/packages/client/ui-session-panel/src/client/element-ids.ts b/packages/client/ui-session-panel/src/client/element-ids.ts new file mode 100644 index 0000000000..f6e881ee55 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/element-ids.ts @@ -0,0 +1,20 @@ +/** DOM ids that connect a Session's toggle and panel across their separate slot entries. */ +import type { SessionId } from '@deepseek-ai/dsh-session/types' + +/** + * Id of a Session's panel element, which the toggle names in `aria-controls`. + * @param sessionId - Session that owns the panel. + * @returns the element id. + */ +export function panelElementId(sessionId: SessionId): string { + return `dsh-session-panel-${sessionId}` +} + +/** + * Id of a Session's toggle, which receives focus when its overlay closes from the keyboard. + * @param sessionId - Session whose header holds the toggle. + * @returns the element id. + */ +export function toggleElementId(sessionId: SessionId): string { + return `dsh-session-panel-toggle-${sessionId}` +} diff --git a/packages/client/ui-session-panel/src/client/index.ts b/packages/client/ui-session-panel/src/client/index.ts new file mode 100644 index 0000000000..b2f9a1d4a9 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/index.ts @@ -0,0 +1,99 @@ +/** + * Session panel plugin, browser half: a Session header toggle and a floating + * panel over the main Conversation body. The panel draws the titles of the + * sections other plugins register and ships the Environment section with the + * project directory row. + */ +import type { Context as ClientContext } from '@deepseek-ai/cordis' +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' +import type { RemoteHostFacts } from '@deepseek-ai/dsh-api-remotes/client' +import type {} from '@deepseek-ai/dsh-client-locale/client' +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import { EnvironmentSection } from './EnvironmentSection.tsx' +import { ProjectRow } from './ProjectRow.tsx' +import { SessionPanel } from './SessionPanel.tsx' +import { SessionPanelToggle } from './SessionPanelToggle.tsx' +import { sectionSource } from './sections.ts' +import type { ProjectRowInjected, SessionPanelInjected, SessionPanelToggleInjected } from './slots.ts' +import { SessionPanelState } from './visibility.ts' +import { de, en, es, fr, ja, NS, pt, ru, zh, type SessionPanelKey } from './locales.ts' + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface LocaleNamespaceMap { + /** Session panel copy. */ + sessionPanel: SessionPanelKey + } +} + +export type { + EnvironmentSectionProps, ProjectRowInjected, ProjectRowProps, SessionPanelInjected, + SessionPanelPresentation, SessionPanelProps, SessionPanelSectionEntry, SessionPanelSectionOwnerProps, + SessionPanelToggleInjected, SessionPanelToggleProps, SessionPanelVisibility, +} from './slots.ts' + +/** Required services: the slot registry, dictionaries, Conversation layout, and the Host facts of the Remote carrier. */ +export const inject = ['slots', 'locale', 'uiConversation', 'remote'] + +/** + * Client plugin body: register the dictionaries, the header toggle, the panel, + * and the Environment section with its project row. + * @param ctx - client root context. + */ +export function apply(ctx: ClientContext): void { + ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'ui-session-panel: dictionaries') + const t = ctx.locale.bind(NS) + const state = new SessionPanelState() + const sections = sectionSource(ctx) + const host: ObservableSnapshot = { + getSnapshot: () => ctx.remote.$host, + subscribe: listener => ctx.on('connection/reset', listener), + } + + ctx.slots.inject('conversation.session.header.utilities', () => ctx.slots.register({ + name: 'conversation.session.header.utilities', + id: 'session-panel', + // The first utility: left of change requests, sharing, and the schedule catalog. + order: -10, + locale: NS, + children: { + 'conversation.session.panel.indicator': { kind: 'list', scope: 'session', inline: true }, + }, + inject: (sessionId: SessionId): SessionPanelToggleInjected => ({ + hooks: { visibility: state.visibility, layout: ctx.uiConversation.layouts.source(sessionId) }, + toggle: (sessionId, fits) => { state.toggle(sessionId, fits) }, + }), + }, SessionPanelToggle)) + + ctx.slots.inject('conversation.session.panel', () => ctx.slots.register({ + name: 'conversation.session.panel', + locale: NS, + children: { + 'conversation.session.panel.section': { kind: 'list', scope: 'session' }, + 'conversation.session.panel.section.actions': { kind: 'keyed', scope: 'session' }, + }, + inject: (sessionId: SessionId): SessionPanelInjected => ({ + hooks: { visibility: state.visibility, layout: ctx.uiConversation.layouts.source(sessionId), sections }, + closeOverlay: (sessionId) => { state.closeOverlay(sessionId) }, + }), + }, SessionPanel)) + + ctx.slots.inject('conversation.session.panel.section', () => ctx.slots.register({ + name: 'conversation.session.panel.section', + id: 'environment', + order: 0, + label: () => t('section.environment'), + children: { + 'conversation.session.panel.environment.row': { kind: 'list', scope: 'session' }, + }, + }, EnvironmentSection)) + + ctx.slots.inject('conversation.session.panel.environment.row', () => ctx.slots.register({ + name: 'conversation.session.panel.environment.row', + id: 'project', + order: 0, + locale: NS, + inject: (): ProjectRowInjected => ({ hooks: { host } }), + }, ProjectRow)) +} diff --git a/packages/client/ui-session-panel/src/client/locales.ts b/packages/client/ui-session-panel/src/client/locales.ts new file mode 100644 index 0000000000..bdab6fdd5d --- /dev/null +++ b/packages/client/ui-session-panel/src/client/locales.ts @@ -0,0 +1,79 @@ +/** `sessionPanel` namespace dictionaries. */ + +/** Dictionary namespace owned by this plugin. */ +export const NS = 'sessionPanel' + +/** Simplified Chinese dictionary (the key-set source of truth). */ +export const zh = { + 'panel.name': '会话面板', + 'toggle.show': '显示会话面板', + 'toggle.hide': '隐藏会话面板', + 'section.environment': '环境', + 'project.actions': '项目目录操作', +} as const + +/** Every key of the `sessionPanel` namespace. */ +export type SessionPanelKey = keyof typeof zh + +/** English dictionary, key-identical to the Chinese source of truth. */ +export const en: Record = { + 'panel.name': 'Session panel', + 'toggle.show': 'Show session panel', + 'toggle.hide': 'Hide session panel', + 'section.environment': 'Environment', + 'project.actions': 'Project directory actions', +} + +/** Japanese dictionary. */ +export const ja = { + 'panel.name': 'セッションパネル', + 'toggle.show': 'セッションパネルを表示', + 'toggle.hide': 'セッションパネルを非表示', + 'section.environment': '環境', + 'project.actions': 'プロジェクトディレクトリの操作', +} satisfies Record + +/** Spanish dictionary. */ +export const es = { + 'panel.name': 'Panel de la sesión', + 'toggle.show': 'Mostrar el panel de la sesión', + 'toggle.hide': 'Ocultar el panel de la sesión', + 'section.environment': 'Entorno', + 'project.actions': 'Acciones del directorio del proyecto', +} satisfies Record + +/** French dictionary. */ +export const fr = { + 'panel.name': 'Panneau de session', + 'toggle.show': 'Afficher le panneau de session', + 'toggle.hide': 'Masquer le panneau de session', + 'section.environment': 'Environnement', + 'project.actions': 'Actions sur le dossier du projet', +} satisfies Record + +/** German dictionary. */ +export const de = { + 'panel.name': 'Sitzungsbereich', + 'toggle.show': 'Sitzungsbereich anzeigen', + 'toggle.hide': 'Sitzungsbereich ausblenden', + 'section.environment': 'Umgebung', + 'project.actions': 'Aktionen für das Projektverzeichnis', +} satisfies Record + +/** Russian dictionary. */ +export const ru = { + 'panel.name': 'Панель сеанса', + 'toggle.show': 'Показать панель сеанса', + 'toggle.hide': 'Скрыть панель сеанса', + 'section.environment': 'Среда', + 'project.actions': 'Действия с каталогом проекта', +} satisfies Record + +/** Brazilian Portuguese dictionary. */ +export const pt = { + 'panel.name': 'Painel da sessão', + 'toggle.show': 'Mostrar painel da sessão', + 'toggle.hide': 'Ocultar painel da sessão', + 'section.environment': 'Ambiente', + 'project.actions': 'Ações da pasta do projeto', +} satisfies Record diff --git a/packages/client/ui-session-panel/src/client/sections.ts b/packages/client/ui-session-panel/src/client/sections.ts new file mode 100644 index 0000000000..fcc9feed5e --- /dev/null +++ b/packages/client/ui-session-panel/src/client/sections.ts @@ -0,0 +1,66 @@ +/** Projection of the section list's registrations into the titles the panel draws. */ +import type { Context as ClientContext } from '@deepseek-ai/cordis' +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import { resolveSlotLabel, type StoredEntry } from '@deepseek-ai/dsh-client-ui-slots' +import type { SessionPanelSectionEntry } from './slots.ts' + +const SECTION_SLOT = 'conversation.session.panel.section' + +/** + * Project live section registrations in display order. A registration + * without a label cannot be titled; it is reported and left out. + * @param entries - shadowing winners of the section list in ledger order. + * @param report - receives one message per unlabeled registration. + * @returns sections ordered by ascending `order`, then registration order. + */ +export function projectSections( + entries: readonly StoredEntry[], report: (message: string) => void, +): readonly SessionPanelSectionEntry[] { + const rows: (SessionPanelSectionEntry & { readonly order: number })[] = [] + for (const entry of entries) { + /* v8 ignore next -- list registration validates id at load. */ + const id = entry.options.id ?? '' + const label = resolveSlotLabel(entry.options.label) + if (label === undefined || label === '') { + report(`ui-session-panel: section "${id}" from ${entry.registrant ?? 'an unknown registrant'} has no label and is not shown`) + continue + } + rows.push({ id, label, order: entry.options.order ?? 0 }) + } + return rows.sort((a, b) => a.order - b.order).map(({ id, label }) => ({ id, label })) +} + +/** + * Observable section roster: recomputed when the section list's ledger or + * the active locale changes, and identity-stable between changes. + * @param ctx - client context whose slot registry and locale the roster follows. + * @returns the section source. + */ +export function sectionSource(ctx: ClientContext): ObservableSnapshot { + let version = -1 + let revision = -1 + let sections: readonly SessionPanelSectionEntry[] = [] + return { + getSnapshot: () => { + const nextVersion = ctx.slots.getVersion(SECTION_SLOT) + const nextRevision = ctx.locale.getSnapshot().revision + if (nextVersion !== version || nextRevision !== revision) { + const reportOnce = version !== nextVersion + version = nextVersion + revision = nextRevision + sections = projectSections(ctx.slots.entriesOfSlot(SECTION_SLOT), (message) => { + if (reportOnce) console.error(message) + }) + } + return sections + }, + subscribe: (listener) => { + const offLedger = ctx.slots.subscribe(SECTION_SLOT, listener) + const offLocale = ctx.locale.subscribe(listener) + return () => { + offLedger() + offLocale() + } + }, + } +} diff --git a/packages/client/ui-session-panel/src/client/slots.ts b/packages/client/ui-session-panel/src/client/slots.ts new file mode 100644 index 0000000000..9cc9fc259d --- /dev/null +++ b/packages/client/ui-session-panel/src/client/slots.ts @@ -0,0 +1,132 @@ +/** Session panel slot declarations and composed component props. */ +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { + InjectFace, PropsLocale, PropsRenderFactories, PropsRenderSlots, PropsRuntime, +} from '@deepseek-ai/dsh-client-ui-slots' +import type { RemoteHostFacts } from '@deepseek-ai/dsh-api-remotes/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { ConversationLayout } from '@deepseek-ai/dsh-client-ui-conversation/client' +import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' +import type {} from '@deepseek-ai/dsh-client-ui-session/client' +import type { NS } from './locales.ts' + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface SlotMap { + /** + * Sections of the Session panel. `id` addresses the section, `order` sorts + * the sections ascending, and the required `label` is the section title, + * which the panel draws. A section with nothing to show renders nothing, + * and the panel hides its title with it. + */ + 'conversation.session.panel.section': { + kind: 'list' + scope: 'session' + owner: SessionPanelSectionOwnerProps + } + /** Trailing controls of one section title, keyed by the section's `id`. */ + 'conversation.session.panel.section.actions': { kind: 'keyed'; scope: 'session' } + /** + * Marks over the panel toggle, such as an attention dot. They stay visible + * while the panel is hidden; each occupant includes text that names it for + * assistive technology, which becomes part of the toggle's name. + */ + 'conversation.session.panel.indicator': { kind: 'list'; scope: 'session'; inline: true } + /** Rows of the built-in Environment section in ascending `order`. */ + 'conversation.session.panel.environment.row': { kind: 'list'; scope: 'session' } + } +} + +/** How the panel currently shows. */ +export type SessionPanelPresentation = + /** Beside the transcript in the body's end gutter. */ + | 'docked' + /** Over the transcript, opened from the toggle while the gutter is too narrow. */ + | 'overlay' + +/** Values every section receives from the panel. */ +export interface SessionPanelSectionOwnerProps { + /** Current presentation; sections may lower their density in the overlay. */ + readonly presentation: SessionPanelPresentation + /** Close the overlay, for example after a row opened another surface; no effect while docked. */ + readonly dismissOverlay: () => void +} + +/** One section the panel draws, projected from the section list's registrations. */ +export interface SessionPanelSectionEntry { + /** Registration id. */ + readonly id: string + /** Localized title. */ + readonly label: string +} + +/** Panel visibility shared by the toggle and the panel. */ +export interface SessionPanelVisibility { + /** Whether the panel docks while the gutter has room; persisted across reloads. */ + readonly pinned: boolean + /** Session whose overlay is open, or null. */ + readonly overlay: SessionId | null +} + +/** Business face of the header toggle. */ +export interface SessionPanelToggleInjected { + /** Shared visibility and the Session's main body layout; the renderer binds them as `useVisibility` and `useLayout`. */ + readonly hooks: { + readonly visibility: ObservableSnapshot + readonly layout: ObservableSnapshot + } + /** + * Show or hide the panel. With room to dock this flips the docking + * preference and closes any overlay; otherwise it opens or closes the + * Session's overlay. + * @param sessionId - Session whose header holds the toggle. + * @param fits - whether the main body's gutter can hold the docked panel now. + */ + readonly toggle: (sessionId: SessionId, fits: boolean) => void +} + +/** Business face of the panel. */ +export interface SessionPanelInjected { + /** Shared visibility, the Session's main body layout, and the projected section roster. */ + readonly hooks: { + readonly visibility: ObservableSnapshot + readonly layout: ObservableSnapshot + readonly sections: ObservableSnapshot + } + /** + * Close the Session's overlay. + * @param sessionId - Session whose overlay closes; another Session's overlay stays. + */ + readonly closeOverlay: (sessionId: SessionId) => void +} + +/** Business face of the project row. */ +export interface ProjectRowInjected { + /** Host facts from the connection's ready frame; the renderer binds them as `useHost`. */ + readonly hooks: { readonly host: ObservableSnapshot } +} + +/** Full props of the header toggle. */ +export type SessionPanelToggleProps = + PropsRuntime<'conversation.session.header.utilities'> + & PropsRenderSlots<'conversation.session.panel.indicator'> + & InjectFace + & PropsLocale + +/** Full props of the panel. */ +export type SessionPanelProps = + PropsRuntime<'conversation.session.panel'> + & PropsRenderSlots<'conversation.session.panel.section' | 'conversation.session.panel.section.actions'> + & InjectFace + & PropsLocale + +/** Full props of the built-in Environment section. */ +export type EnvironmentSectionProps = + PropsRuntime<'conversation.session.panel.section'> + & PropsRenderSlots<'conversation.session.panel.environment.row'> + +/** Full props of the project row. */ +export type ProjectRowProps = + PropsRuntime<'conversation.session.panel.environment.row'> + & PropsRenderFactories + & InjectFace + & PropsLocale diff --git a/packages/client/ui-session-panel/src/client/visibility.ts b/packages/client/ui-session-panel/src/client/visibility.ts new file mode 100644 index 0000000000..627959db05 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/visibility.ts @@ -0,0 +1,89 @@ +/** Session panel visibility: the persisted docking preference, the transient overlay, and their presentation. */ +import { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { ConversationLayout } from '@deepseek-ai/dsh-client-ui-conversation/client' +import type { SessionPanelPresentation, SessionPanelVisibility } from './slots.ts' + +/** localStorage key of the docking preference. */ +export const PINNED_STORAGE_KEY = 'dsh.sessionPanel.pinned' + +/** + * Smallest end gutter that holds the docked panel, in CSS px: 48px clear of + * the transcript column (past the width handle's 24px offset and 10px strip), + * the panel's 280px minimum width, and a 16px edge margin. + */ +export const DOCK_MIN_GUTTER = 344 + +/** + * Whether the main body's end gutter can hold the docked panel. + * @param layout - main body geometry of the Session. + * @returns true when the panel can dock without covering the transcript. + */ +export function fitsLayout(layout: ConversationLayout): boolean { + return layout.endGutter >= DOCK_MIN_GUTTER +} + +/** + * Decide how the panel shows for one Session. + * @param fits - whether the gutter can hold the docked panel. + * @param visibility - shared visibility state. + * @param sessionId - Session whose panel is decided. + * @returns the presentation, or `hidden` when the panel renders nothing. + */ +export function presentationOf( + fits: boolean, visibility: SessionPanelVisibility, sessionId: SessionId, +): SessionPanelPresentation | 'hidden' { + if (fits) return visibility.pinned ? 'docked' : 'hidden' + return visibility.overlay === sessionId ? 'overlay' : 'hidden' +} + +/** + * Visibility shared by every Session's toggle and panel. Docking follows one + * preference for all Sessions; at most one Session's overlay is open. + */ +export class SessionPanelState { + // A stored value other than `false` keeps the default: the panel docks. + private readonly pinned = createSnapshotStore(true, { persist: { name: PINNED_STORAGE_KEY } }) + private readonly overlay = createSnapshotStore(null) + private current: SessionPanelVisibility = { pinned: this.pinned.getSnapshot() !== false, overlay: null } + + /** Combined visibility; the snapshot keeps its identity until a member changes. */ + readonly visibility: ObservableSnapshot = { + getSnapshot: () => { + const pinned = this.pinned.getSnapshot() !== false + const overlay = this.overlay.getSnapshot() + if (pinned !== this.current.pinned || overlay !== this.current.overlay) this.current = { pinned, overlay } + return this.current + }, + subscribe: (listener) => { + const offPinned = this.pinned.subscribe(listener) + const offOverlay = this.overlay.subscribe(listener) + return () => { + offPinned() + offOverlay() + } + }, + } + + /** + * Show or hide the panel from a Session's toggle. + * @param sessionId - Session whose header holds the toggle. + * @param fits - whether the gutter can hold the docked panel now. + */ + toggle(sessionId: SessionId, fits: boolean): void { + if (fits) { + this.pinned.set(!this.visibility.getSnapshot().pinned) + this.overlay.set(null) + return + } + this.overlay.set(this.overlay.getSnapshot() === sessionId ? null : sessionId) + } + + /** + * Close a Session's overlay. + * @param sessionId - Session whose overlay closes; another Session's overlay stays open. + */ + closeOverlay(sessionId: SessionId): void { + if (this.overlay.getSnapshot() === sessionId) this.overlay.set(null) + } +} diff --git a/packages/client/ui-session-panel/src/css-modules.d.ts b/packages/client/ui-session-panel/src/css-modules.d.ts new file mode 100644 index 0000000000..8811db1264 --- /dev/null +++ b/packages/client/ui-session-panel/src/css-modules.d.ts @@ -0,0 +1,4 @@ +declare module '*.module.css' { + const classes: Record + export default classes +} diff --git a/packages/client/ui-session-panel/src/index.ts b/packages/client/ui-session-panel/src/index.ts new file mode 100644 index 0000000000..76ee1f0c6a --- /dev/null +++ b/packages/client/ui-session-panel/src/index.ts @@ -0,0 +1,9 @@ +/** + * Node half of the Session panel plugin. The browser half in `src/client/` + * owns every contribution; this entry exists so the package appears as an + * ordinary Loader row. + * @module @deepseek-ai/dsh-client-ui-session-panel + */ + +/** Loader-visible no-op body; the browser half carries the feature. */ +export function apply(): void {} diff --git a/packages/client/ui-session-panel/tests/browser-plugin.client.spec.ts b/packages/client/ui-session-panel/tests/browser-plugin.client.spec.ts new file mode 100644 index 0000000000..d65e7daf10 --- /dev/null +++ b/packages/client/ui-session-panel/tests/browser-plugin.client.spec.ts @@ -0,0 +1,144 @@ +/** + * ui-session-panel plugin halves: the browser entry's dictionaries, header + * toggle, panel, Environment section, and project row against the real + * SlotRegistry, the inject faces those entries receive, the section roster + * projection, fiber teardown removing every contribution (HMR safety), and + * the inert node entry. + */ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import { stubConfigForm } from '@deepseek-ai/dsh-client-test-runtime' +import { apply as applyLocale, inject as localeInject } from '@deepseek-ai/dsh-client-locale/client' +import type { ConversationLayout } from '@deepseek-ai/dsh-client-ui-conversation/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { apply, inject } from '../src/client/index.ts' +import type { ProjectRowInjected, SessionPanelInjected, SessionPanelToggleInjected } from '../src/client/slots.ts' +import { apply as applyNode } from '../src/index.ts' + +const SID = 'session-1' as SessionId + +afterEach(() => { + vi.restoreAllMocks() +}) + +/** Boot the browser half over a real slot tree that declares the header utilities and the panel seat. */ +async function bench() { + const ctx = new Context() + await ctx.plugin(SlotRegistry).await() + ctx.slots.register({ + name: 'root', + children: { + 'conversation.session.header.utilities': { kind: 'list', scope: 'session' }, + 'conversation.session.panel': { kind: 'single', scope: 'session' }, + }, + } as never, () => null) + const layout = createSnapshotStore({ endGutter: 400 }) + const layoutSources: SessionId[] = [] + ctx.provide('uiConversation', { + layouts: { + source: (sessionId: SessionId) => { + layoutSources.push(sessionId) + return layout + }, + }, + } as never) + const host = { home: '/Users/me', isLoopback: true } + ctx.provide('connection', { api: { settings: {} }, isLoopback: false } as never) + ctx.provide('remote', { $on: () => () => {}, $host: host } as never) + ctx.provide('configForms', { developerTools: { enabled: createSnapshotStore(true) }, get: () => stubConfigForm().scope } as never) + await ctx.plugin({ inject: localeInject, apply: applyLocale }).await() + ctx.locale.setLocale('zh') + const fiber = ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + return { ctx, fiber, layout, layoutSources, host } +} + +/** Inject face of one registration, called for the test Session. */ +function faceOf(ctx: Context, slot: string, id: string | undefined): unknown { + const entry = ctx.slots.entries(slot as never).find(candidate => candidate.options.id === id) + const face = entry?.inject as ((sessionId: SessionId) => unknown) | undefined + if (face === undefined) throw new Error(`${slot} entry ${id ?? '(single)'} registered no inject face`) + return face(SID) +} + +describe('ui-session-panel browser half', () => { + it('declares the services it binds', () => { + expect(inject).toEqual(['slots', 'locale', 'uiConversation', 'remote']) + }) + + it('registers the toggle first among the header utilities, the panel, the Environment section, and the project row', async () => { + const { ctx } = await bench() + const toggle = ctx.slots.entries('conversation.session.header.utilities').find(entry => entry.options.id === 'session-panel') + expect(toggle?.options.order).toBe(-10) + expect(ctx.slots.entries('conversation.session.panel')).toHaveLength(1) + const section = ctx.slots.entries('conversation.session.panel.section').find(entry => entry.options.id === 'environment') + expect(section?.options.order).toBe(0) + expect(ctx.slots.entries('conversation.session.panel.environment.row').map(entry => entry.options.id)).toEqual(['project']) + }) + + it('hands the toggle and the panel the shared visibility and the Session layout source', async () => { + const { ctx, layout, layoutSources } = await bench() + const toggle = faceOf(ctx, 'conversation.session.header.utilities', 'session-panel') as SessionPanelToggleInjected + const panel = faceOf(ctx, 'conversation.session.panel', undefined) as SessionPanelInjected + expect(toggle.hooks.layout).toBe(layout) + expect(panel.hooks.layout).toBe(layout) + expect(layoutSources).toEqual([SID, SID]) + expect(toggle.hooks.visibility).toBe(panel.hooks.visibility) + toggle.toggle(SID, false) + expect(panel.hooks.visibility.getSnapshot()).toEqual({ pinned: true, overlay: SID }) + panel.closeOverlay(SID) + expect(panel.hooks.visibility.getSnapshot().overlay).toBeNull() + }) + + it('projects the section roster in the active locale and keeps it stable between changes', async () => { + const { ctx } = await bench() + const panel = faceOf(ctx, 'conversation.session.panel', undefined) as SessionPanelInjected + const roster = panel.hooks.sections + const first = roster.getSnapshot() + expect(first).toEqual([{ id: 'environment', label: '环境' }]) + expect(roster.getSnapshot()).toBe(first) + const listener = vi.fn() + const off = roster.subscribe(listener) + ctx.locale.setLocale('en') + expect(listener).toHaveBeenCalled() + expect(roster.getSnapshot()).toEqual([{ id: 'environment', label: 'Environment' }]) + + const error = vi.spyOn(console, 'error').mockImplementation(() => {}) + const dispose = ctx.slots.register({ name: 'conversation.session.panel.section', id: 'untitled', order: 5 }, () => null) + expect(roster.getSnapshot()).toEqual([{ id: 'environment', label: 'Environment' }]) + roster.getSnapshot() + expect(error).toHaveBeenCalledTimes(1) + ctx.locale.setLocale('zh') + roster.getSnapshot() + expect(error).toHaveBeenCalledTimes(1) + dispose() + off() + }) + + it('gives the project row the Host facts and follows connection resets', async () => { + const { ctx, host } = await bench() + const row = faceOf(ctx, 'conversation.session.panel.environment.row', 'project') as ProjectRowInjected + expect(row.hooks.host.getSnapshot()).toBe(host) + const listener = vi.fn() + const off = row.hooks.host.subscribe(listener) + ctx.emit('connection/reset' as never) + expect(listener).toHaveBeenCalledTimes(1) + off() + }) + + it('removes every contribution with the fiber (HMR safety)', async () => { + const { ctx, fiber } = await bench() + await fiber.dispose() + expect(ctx.slots.entries('conversation.session.header.utilities')).toHaveLength(0) + expect(ctx.slots.entries('conversation.session.panel')).toHaveLength(0) + expect(ctx.slots.entries('conversation.session.panel.section')).toHaveLength(0) + }) +}) + +describe('ui-session-panel node half', () => { + it('contributes no host behavior', () => { + expect(applyNode).not.toThrow() + }) +}) diff --git a/packages/client/ui-session-panel/tests/components.client.spec.tsx b/packages/client/ui-session-panel/tests/components.client.spec.tsx new file mode 100644 index 0000000000..ecdf182cdf --- /dev/null +++ b/packages/client/ui-session-panel/tests/components.client.spec.tsx @@ -0,0 +1,272 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import type { ReactNode } from 'react' +import { contextMenuHook, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { ConversationLayout } from '@deepseek-ai/dsh-client-ui-conversation/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { EnvironmentSection } from '../src/client/EnvironmentSection.tsx' +import { ProjectRow } from '../src/client/ProjectRow.tsx' +import { SessionPanel } from '../src/client/SessionPanel.tsx' +import { SessionPanelToggle } from '../src/client/SessionPanelToggle.tsx' +import type { + EnvironmentSectionProps, ProjectRowProps, SessionPanelProps, SessionPanelSectionEntry, + SessionPanelSectionOwnerProps, SessionPanelToggleProps, SessionPanelVisibility, +} from '../src/client/slots.ts' +import { DOCK_MIN_GUTTER } from '../src/client/visibility.ts' +import { en, zh } from '../src/client/locales.ts' + +const SID = 'session-1' as SessionId +const t = makeTranslate(zh) as SessionPanelToggleProps['t'] +const WIDE: ConversationLayout = { endGutter: DOCK_MIN_GUTTER } +const NARROW: ConversationLayout = { endGutter: DOCK_MIN_GUTTER - 1 } +const DOCKED: SessionPanelVisibility = { pinned: true, overlay: null } + +function selectorOf(value: T) { + return (select: (current: T) => S): S => select(value) +} + +beforeEach(() => { + vi.stubGlobal('ResizeObserver', class { + observe(): void {} + unobserve(): void {} + disconnect(): void {} + }) + vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true, addEventListener() {}, removeEventListener() {} }))) +}) + +afterEach(() => { + cleanup() + vi.unstubAllGlobals() +}) + +describe('SessionPanelToggle', () => { + function toggleProps(layout: ConversationLayout, visibility: SessionPanelVisibility, toggle = vi.fn()) { + const renderSlot = vi.fn(() => 需要处理) + const props = { + sessionId: SID, useLayout: selectorOf(layout), useVisibility: selectorOf(visibility), toggle, renderSlot, t, + } as SessionPanelToggleProps + return { props, toggle, renderSlot } + } + + it('names the panel together with its indicators and reports the docked panel as expanded', () => { + const { props, renderSlot } = toggleProps(WIDE, DOCKED) + render() + const button = screen.getByRole('button', { name: '会话面板 需要处理' }) + expect(button.getAttribute('aria-expanded')).toBe('true') + expect(button.getAttribute('aria-controls')).toBe(`dsh-session-panel-${SID}`) + expect(renderSlot).toHaveBeenCalledWith('conversation.session.panel.indicator', {}) + }) + + it('flips docking with room to dock and opens the overlay without it', () => { + const wide = toggleProps(WIDE, DOCKED) + render() + fireEvent.click(screen.getByRole('button')) + expect(wide.toggle).toHaveBeenCalledWith(SID, true) + cleanup() + const narrow = toggleProps(NARROW, DOCKED) + render() + const button = screen.getByRole('button') + expect(button.getAttribute('aria-expanded')).toBe('false') + expect(button.hasAttribute('aria-controls')).toBe(false) + fireEvent.click(button) + expect(narrow.toggle).toHaveBeenCalledWith(SID, false) + }) + + it('reports an open overlay as expanded', () => { + const { props } = toggleProps(NARROW, { pinned: false, overlay: SID }) + render() + expect(screen.getByRole('button').getAttribute('aria-expanded')).toBe('true') + }) +}) + +describe('SessionPanel', () => { + const SECTIONS: readonly SessionPanelSectionEntry[] = [ + { id: 'environment', label: '环境' }, + { id: 'change-requests', label: '变更请求' }, + ] + + function panelProps(layout: ConversationLayout, visibility: SessionPanelVisibility, closeOverlay = vi.fn()) { + const owners: SessionPanelSectionOwnerProps[] = [] + const renderSlot = ((key: string, owner: object, opts?: { only?: string; entryKey?: string }): ReactNode => { + if (key === 'conversation.session.panel.section.actions') { + return opts?.entryKey === 'change-requests' ? : null + } + owners.push(owner as SessionPanelSectionOwnerProps) + return

{`${opts?.only ?? ''} body`}

+ }) as SessionPanelProps['renderSlot'] + const props = { + sessionId: SID, + useLayout: selectorOf(layout), + useVisibility: selectorOf(visibility), + useSections: selectorOf(SECTIONS), + closeOverlay, + renderSlot, + t, + } as SessionPanelProps + return { props, owners, closeOverlay } + } + + it('renders nothing while hidden', () => { + const { props } = panelProps(WIDE, { pinned: false, overlay: null }) + const view = render() + expect(view.container.innerHTML).toBe('') + }) + + it('docks with one titled region per section in roster order and each section body', () => { + const { props, owners } = panelProps(WIDE, DOCKED) + render() + const panel = screen.getByRole('complementary', { name: '会话面板' }) + expect(panel.getAttribute('data-session-panel')).toBe('docked') + expect(panel.id).toBe(`dsh-session-panel-${SID}`) + const regions = screen.getAllByRole('region') + expect(regions.map(region => region.getAttribute('aria-labelledby'))).toEqual([ + `dsh-session-panel-${SID}-environment`, `dsh-session-panel-${SID}-change-requests`, + ]) + expect(screen.getByRole('heading', { name: '变更请求' })).toBeTruthy() + expect(screen.getByText('environment body')).toBeTruthy() + expect(screen.getByRole('button', { name: '刷新' })).toBeTruthy() + expect(owners.every(owner => owner.presentation === 'docked')).toBe(true) + }) + + it('closes the overlay on Escape from inside and returns focus to the toggle', () => { + const { props, owners, closeOverlay } = panelProps(NARROW, { pinned: true, overlay: SID }) + const toggle = document.createElement('button') + toggle.id = `dsh-session-panel-toggle-${SID}` + document.body.append(toggle) + try { + render() + const panel = screen.getByRole('complementary') + expect(panel.getAttribute('data-session-panel')).toBe('overlay') + fireEvent.keyDown(document, { key: 'Enter' }) + expect(closeOverlay).not.toHaveBeenCalled() + screen.getByRole('button', { name: '刷新' }).focus() + fireEvent.keyDown(document.activeElement as Element, { key: 'Escape' }) + expect(closeOverlay).toHaveBeenCalledWith(SID) + expect(document.activeElement).toBe(toggle) + owners[0]?.dismissOverlay() + expect(closeOverlay).toHaveBeenCalledTimes(2) + } finally { + toggle.remove() + } + }) + + it('closes the overlay on Escape from the page without moving focus', () => { + const { props, closeOverlay } = panelProps(NARROW, { pinned: true, overlay: SID }) + render() + const outside = document.createElement('input') + document.body.append(outside) + try { + outside.focus() + fireEvent.keyDown(outside, { key: 'Escape' }) + expect(closeOverlay).toHaveBeenCalledWith(SID) + expect(document.activeElement).toBe(outside) + } finally { + outside.remove() + } + }) + + it('closes the overlay on an outside pointerdown but not on the panel, the toggle, or an open menu', () => { + const { props, closeOverlay } = panelProps(NARROW, { pinned: true, overlay: SID }) + const toggle = document.createElement('button') + toggle.id = `dsh-session-panel-toggle-${SID}` + const menu = document.createElement('div') + menu.setAttribute('role', 'menu') + const item = document.createElement('button') + menu.append(item) + document.body.append(toggle, menu) + try { + render() + fireEvent.pointerDown(screen.getByText('environment body')) + fireEvent.pointerDown(toggle) + fireEvent.pointerDown(item) + expect(closeOverlay).not.toHaveBeenCalled() + fireEvent.pointerDown(document.body) + expect(closeOverlay).toHaveBeenCalledWith(SID) + } finally { + toggle.remove() + menu.remove() + } + }) + + it('leaves Escape to other handlers while docked, after another handler took it, or behind a modal', () => { + const docked = panelProps(WIDE, DOCKED) + render() + fireEvent.keyDown(document, { key: 'Escape' }) + fireEvent.pointerDown(document.body) + expect(docked.closeOverlay).not.toHaveBeenCalled() + cleanup() + const overlay = panelProps(NARROW, { pinned: true, overlay: SID }) + render() + const event = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }) + event.preventDefault() + document.dispatchEvent(event) + expect(overlay.closeOverlay).not.toHaveBeenCalled() + }) +}) + +describe('EnvironmentSection', () => { + it('renders its rows straight into the section body', () => { + const renderSlot = vi.fn(() => row) + render(<>{EnvironmentSection({ renderSlot } as EnvironmentSectionProps)}) + expect(renderSlot).toHaveBeenCalledWith('conversation.session.panel.environment.row', {}) + expect(screen.getByText('row')).toBeTruthy() + }) +}) + +describe('ProjectRow', () => { + function rowProps(over: { + workspacePath?: string + cwd?: string + home?: string + }, open = vi.fn()) { + const renderFactorySlot = vi.fn((_name: string, input: { label: string }) => ) + const props = { + sessionId: SID, + useWorkspaces: selectorOf({ + items: over.workspacePath === undefined ? [] : [{ path: over.workspacePath, sessionIds: [SID] }], + }), + useSessions: selectorOf({ byId: over.cwd === undefined ? {} : { [SID]: { cwd: over.cwd } } }), + useHost: selectorOf({ home: over.home, isLoopback: true }), + useContextMenu: contextMenuHook(open), + renderFactorySlot, + t, + } as ProjectRowProps + return { props, renderFactorySlot, open } + } + + it('shows the listing Workspace directory with the home directory abbreviated', () => { + const { props, renderFactorySlot } = rowProps({ + workspacePath: '/Users/me/projects/deepseek-harness', cwd: '/Users/me/elsewhere', home: '/Users/me', + }) + const view = render() + const label = view.container.querySelector('[data-path-label]') as HTMLElement + expect(label.getAttribute('title')).toBe('~/projects/deepseek-harness') + expect(renderFactorySlot).toHaveBeenCalledWith('contextMenu.button', expect.objectContaining({ + target: { kind: 'directory', value: { sessionId: SID, path: '/Users/me/projects/deepseek-harness' } }, + label: '项目目录操作', + size: 'sm', + })) + expect(screen.getByRole('button', { name: '项目目录操作' })).toBeTruthy() + }) + + it('falls back to the directory the Session was created in and opens the directory menu on right-click', () => { + const { props, open } = rowProps({ cwd: '/srv/app' }) + const view = render() + expect(view.container.querySelector('[data-path-label]')?.getAttribute('title')).toBe('/srv/app') + fireEvent.contextMenu(view.container.querySelector('[data-session-panel-project]') as HTMLElement) + expect(open).toHaveBeenCalledWith({ kind: 'directory', value: { sessionId: SID, path: '/srv/app' } }, expect.anything()) + }) + + it('renders nothing before the Session directory is known', () => { + const { props } = rowProps({}) + const view = render() + expect(view.container.innerHTML).toBe('') + }) +}) + +describe('dictionaries', () => { + it('keeps the English dictionary key-identical to the Chinese source of truth', () => { + expect(Object.keys(en).sort()).toEqual(Object.keys(zh).sort()) + }) +}) diff --git a/packages/client/ui-session-panel/tests/sections.client.spec.ts b/packages/client/ui-session-panel/tests/sections.client.spec.ts new file mode 100644 index 0000000000..5500f97256 --- /dev/null +++ b/packages/client/ui-session-panel/tests/sections.client.spec.ts @@ -0,0 +1,43 @@ +import { describe, expect, it, vi } from 'vitest' +import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots' +import { projectSections } from '../src/client/sections.ts' + +function entry(id: string, order: number | undefined, label: StoredEntry['options']['label'], registrant?: string): StoredEntry { + return { + component: () => null, + options: { id, ...order === undefined ? {} : { order }, ...label === undefined ? {} : { label } }, + ...registrant === undefined ? {} : { registrant }, + } +} + +describe('projectSections', () => { + it('orders sections by ascending order, keeping registration order for ties, and resolves locale thunks', () => { + const report = vi.fn() + const sections = projectSections([ + entry('later', 100, 'Change requests'), + entry('first', 0, () => 'Environment'), + entry('tie', 100, 'Outputs'), + entry('default', undefined, 'Default order'), + ], report) + expect(sections).toEqual([ + { id: 'first', label: 'Environment' }, + { id: 'default', label: 'Default order' }, + { id: 'later', label: 'Change requests' }, + { id: 'tie', label: 'Outputs' }, + ]) + expect(report).not.toHaveBeenCalled() + }) + + it('reports and leaves out a section that cannot be titled', () => { + const report = vi.fn() + const sections = projectSections([ + entry('untitled', 0, undefined, 'acme-plugin'), + entry('blank', 1, ''), + entry('titled', 2, 'Titled'), + ], report) + expect(sections).toEqual([{ id: 'titled', label: 'Titled' }]) + expect(report).toHaveBeenCalledTimes(2) + expect(report.mock.calls[0]?.[0]).toContain('"untitled" from acme-plugin') + expect(report.mock.calls[1]?.[0]).toContain('"blank" from an unknown registrant') + }) +}) diff --git a/packages/client/ui-session-panel/tests/visibility.client.spec.ts b/packages/client/ui-session-panel/tests/visibility.client.spec.ts new file mode 100644 index 0000000000..20d6baabb2 --- /dev/null +++ b/packages/client/ui-session-panel/tests/visibility.client.spec.ts @@ -0,0 +1,89 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { + DOCK_MIN_GUTTER, PINNED_STORAGE_KEY, SessionPanelState, fitsLayout, presentationOf, +} from '../src/client/visibility.ts' + +const A = 'session-a' as SessionId +const B = 'session-b' as SessionId + +beforeEach(() => { localStorage.clear() }) +afterEach(() => { localStorage.clear() }) + +describe('fitsLayout', () => { + it('docks only from the minimum gutter up', () => { + expect(fitsLayout({ endGutter: DOCK_MIN_GUTTER - 1 })).toBe(false) + expect(fitsLayout({ endGutter: DOCK_MIN_GUTTER })).toBe(true) + expect(fitsLayout({ endGutter: 0 })).toBe(false) + }) +}) + +describe('presentationOf', () => { + it.each([ + [true, true, null, 'docked'], + [true, true, A, 'docked'], + [true, false, null, 'hidden'], + [true, false, A, 'hidden'], + [false, true, null, 'hidden'], + [false, false, null, 'hidden'], + [false, true, A, 'overlay'], + [false, false, A, 'overlay'], + [false, true, B, 'hidden'], + ] as const)('fits=%s pinned=%s overlay=%s shows %s', (fits, pinned, overlay, expected) => { + expect(presentationOf(fits, { pinned, overlay }, A)).toBe(expected) + }) +}) + +describe('SessionPanelState', () => { + it('docks by default and keeps the snapshot identity until a member changes', () => { + const state = new SessionPanelState() + const first = state.visibility.getSnapshot() + expect(first).toEqual({ pinned: true, overlay: null }) + expect(state.visibility.getSnapshot()).toBe(first) + }) + + it('flips and persists the docking preference when the gutter has room, closing any overlay', () => { + const state = new SessionPanelState() + state.toggle(A, false) + expect(state.visibility.getSnapshot().overlay).toBe(A) + state.toggle(A, true) + expect(state.visibility.getSnapshot()).toEqual({ pinned: false, overlay: null }) + expect(localStorage.getItem(PINNED_STORAGE_KEY)).toBe('false') + expect(new SessionPanelState().visibility.getSnapshot().pinned).toBe(false) + state.toggle(A, true) + expect(state.visibility.getSnapshot().pinned).toBe(true) + }) + + it('opens and closes one Session overlay without touching the docking preference', () => { + const state = new SessionPanelState() + state.toggle(A, false) + state.toggle(B, false) + expect(state.visibility.getSnapshot()).toEqual({ pinned: true, overlay: B }) + state.closeOverlay(A) + expect(state.visibility.getSnapshot().overlay).toBe(B) + state.toggle(B, false) + expect(state.visibility.getSnapshot().overlay).toBeNull() + state.toggle(A, false) + state.closeOverlay(A) + expect(state.visibility.getSnapshot().overlay).toBeNull() + }) + + it('treats a stored value other than false as the default', () => { + localStorage.setItem(PINNED_STORAGE_KEY, '"yes"') + expect(new SessionPanelState().visibility.getSnapshot().pinned).toBe(true) + }) + + it('notifies subscribers of both members and stops after unsubscribe', () => { + const state = new SessionPanelState() + let calls = 0 + const off = state.visibility.subscribe(() => { calls += 1 }) + state.toggle(A, false) + state.toggle(A, true) + const seen = calls + expect(seen).toBeGreaterThanOrEqual(2) + off() + state.toggle(A, true) + expect(calls).toBe(seen) + }) +}) diff --git a/packages/client/ui-session-panel/tsconfig.json b/packages/client/ui-session-panel/tsconfig.json new file mode 100644 index 0000000000..e07fa99318 --- /dev/null +++ b/packages/client/ui-session-panel/tsconfig.json @@ -0,0 +1,57 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../api/remotes/tsconfig.client.json" + }, + { + "path": "../../api/session-controller/tsconfig.client.json" + }, + { + "path": "../../api/workspace-controller/tsconfig.client.json" + }, + { + "path": "../locale/tsconfig.client.json" + }, + { + "path": "../store" + }, + { + "path": "../ui-context-menu" + }, + { + "path": "../ui-conversation/tsconfig.client.json" + }, + { + "path": "../ui-primitives" + }, + { + "path": "../ui-renderer" + }, + { + "path": "../ui-session" + }, + { + "path": "../ui-slots" + }, + { + "path": "../../core/session" + }, + { + "path": "../../util/workspace-path" + }, + { + "path": "../../workspace/workspace" + } + ] +} diff --git a/packages/client/ui-session-panel/tsdown.config.ts b/packages/client/ui-session-panel/tsdown.config.ts new file mode 100644 index 0000000000..7aa03cebc1 --- /dev/null +++ b/packages/client/ui-session-panel/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts index d3c3aefc0f..cb3cb0e61e 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -814,7 +814,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.composer\', () => ctx.slots.register(\n { name: \'conversation.composer\', select: owner => null },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:290', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:297', }, { key: 'conversation.composer.bar', @@ -857,7 +857,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.composer.bar\', () => ctx.slots.register(\n { name: \'conversation.composer.bar\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:336', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:343', }, { key: 'conversation.composer.dock', @@ -918,7 +918,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.composer.dock\', () => ctx.slots.register(\n { name: \'conversation.composer.dock\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:315', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:322', }, { key: 'conversation.header', @@ -1030,7 +1030,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.agentPreset\', () => ctx.slots.register(\n { name: \'conversation.hero.agentPreset\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:298', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:305', }, { key: 'conversation.hero.brand.mark', @@ -1062,7 +1062,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.brand.mark\', () => ctx.slots.register(\n { name: \'conversation.hero.brand.mark\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:296', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:303', }, { key: 'conversation.hero.frame', @@ -1109,7 +1109,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'wraps-owner-content', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.frame\', () => ctx.slots.register(\n { name: \'conversation.hero.frame\', id: \'my-layer\', order: 100 },\n ({ children }) => React.createElement(\'div\', null, children),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:294', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:301', }, { key: 'conversation.hero.options', @@ -1169,7 +1169,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.options\', () => ctx.slots.register(\n { name: \'conversation.hero.options\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:300', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:307', }, { key: 'conversation.hero.workspace', @@ -1205,7 +1205,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.workspace\', () => ctx.slots.register(\n { name: \'conversation.hero.workspace\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:292', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:299', }, { key: 'conversation.hero.workspace.directoryFlow', @@ -1285,7 +1285,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.activity\', () => ctx.slots.register(\n { name: \'conversation.input.activity\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:331', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:338', }, { key: 'conversation.input.attachments', @@ -1330,7 +1330,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.attachments\', () => ctx.slots.register(\n { name: \'conversation.input.attachments\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:341', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:348', }, { key: 'conversation.input.dock', @@ -1399,7 +1399,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.dock\', () => ctx.slots.register(\n { name: \'conversation.input.dock\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:305', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:312', }, { key: 'conversation.input.left', @@ -1457,7 +1457,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.left\', () => ctx.slots.register(\n { name: \'conversation.input.left\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:320', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:327', }, { key: 'conversation.input.model', @@ -1501,7 +1501,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model\', () => ctx.slots.register(\n { name: \'conversation.input.model\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:362', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:369', }, { key: 'conversation.input.model.label', @@ -1667,7 +1667,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.overlay\', () => ctx.slots.register(\n { name: \'conversation.input.overlay\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:310', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:317', }, { key: 'conversation.input.permission', @@ -1711,7 +1711,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.permission\', () => ctx.slots.register(\n { name: \'conversation.input.permission\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:355', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:362', }, { key: 'conversation.input.plan', @@ -1754,7 +1754,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.plan\', () => ctx.slots.register(\n { name: \'conversation.input.plan\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:350', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:357', }, { key: 'conversation.input.right', @@ -1812,7 +1812,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.right\', () => ctx.slots.register(\n { name: \'conversation.input.right\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:325', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:332', }, { key: 'conversation.plan-review.actions', @@ -2227,6 +2227,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ declaredBy: 'an entry in \'conversation.session.header\' (client-ui-conversation), so it exists while that entry is mounted', occupants: [ 'client-ui-schedule ScheduleCatalogAction id \'schedule-catalog\'', + 'client-ui-session-panel SessionPanelToggle id \'session-panel\'', 'experimental-client-ui-forge HeaderButton id \'forge-panel\'', 'experimental-liveshare LiveshareShareAction id \'liveshare-share\'', ], @@ -2287,7 +2288,278 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header.views.actions\', () => ctx.slots.register(\n { name: \'conversation.session.header.views.actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:283', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:290', + }, + { + key: 'conversation.session.panel', + kind: 'single', + scope: 'session', + summary: 'One floating panel over the main Conversation body\'s end gutter.', + doc: 'One floating panel over the main Conversation body\'s end gutter. It renders\nonly for the main occurrence of a Session in its active phase, never for an\nembedded occurrence or the blank home; the occupant positions itself against\nthe body and reads `ctx.uiConversation.layouts` to keep clear of the transcript.', + registerOptions: [], + ownerProps: [ + '/** The Session panel\'s occupant derives its state from standard Session props. */\nexport interface ConversationSessionPanelOwnerProps {\n /** Marker field: the occupant receives no owner-specific values. */\n children?: never\n}', + ], + ownerPropsReferences: [], + standardProps: [ + 'useRemoteAccess: (action: RemoteEndpoint) => boolean', + 'useResource: UseResource', + 'useContextMenu: UseContextMenu', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessions: UseSessions', + 'useSessionStatus: UseSessionStatus', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', + 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', + 'useChat: UseChat', + 'useConversation: UseConversation', + 'useInput: SnapshotSelectorHook', + 'inputActions: InputActions', + 'useSession: SessionSnapshotSelector', + 'sessionId: SessionId', + 'useProjection: UseProjection', + 'useAccess: (action: RemoteEndpoint) => boolean', + 'useTrajectory: UseTrajectory', + ], + keyDomain: '', + hookContext: '', + slotInject: '', + declaredBy: 'factory \'conversation.content\' (client-ui-conversation), so it exists while that definition is registered', + occupants: [ + 'client-ui-session-panel SessionPanel', + ], + replaceRisk: 'shadows-shipped-ui', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.panel\', () => ctx.slots.register(\n { name: \'conversation.session.panel\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:288', + }, + { + key: 'conversation.session.panel.environment.row', + kind: 'list', + scope: 'session', + summary: 'Rows of the built-in Environment section in ascending `order`.', + doc: 'Rows of the built-in Environment section in ascending `order`.', + registerOptions: [ + { + name: 'id', + requirement: 'required', + type: 'string', + doc: 'Your cell key. Use an id of your own: a fresh id is added beside the shipped entries, while reusing a shipped id puts you in THAT cell and replaces it. Owners that filter by id address you by it.', + }, + { + name: 'order', + requirement: 'optional', + type: 'number', + doc: 'Position among the entries, ascending (default 0).', + }, + { + name: 'label', + requirement: 'optional', + type: 'string | (() => string)', + doc: 'Display text where the owner projects one (nav rows, tabs). A thunk is re-read on every projection, so localized text follows the active locale without re-registering.', + }, + ], + ownerProps: [], + ownerPropsReferences: [], + standardProps: [ + 'useRemoteAccess: (action: RemoteEndpoint) => boolean', + 'useResource: UseResource', + 'useContextMenu: UseContextMenu', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessions: UseSessions', + 'useSessionStatus: UseSessionStatus', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', + 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', + 'useChat: UseChat', + 'useConversation: UseConversation', + 'useInput: SnapshotSelectorHook', + 'inputActions: InputActions', + 'useSession: SessionSnapshotSelector', + 'sessionId: SessionId', + 'useProjection: UseProjection', + 'useAccess: (action: RemoteEndpoint) => boolean', + 'useTrajectory: UseTrajectory', + ], + keyDomain: '', + hookContext: '', + slotInject: '', + declaredBy: 'an entry in \'conversation.session.panel.section\' (client-ui-session-panel), so it exists while that entry is mounted', + occupants: [ + 'client-ui-session-panel ProjectRow id \'project\'', + ], + replaceRisk: 'none', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.panel.environment.row\', () => ctx.slots.register(\n { name: \'conversation.session.panel.environment.row\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/client/ui-session-panel/src/client/slots.ts:35', + }, + { + key: 'conversation.session.panel.indicator', + kind: 'list', + scope: 'session', + summary: 'Marks over the panel toggle, such as an attention dot.', + doc: 'Marks over the panel toggle, such as an attention dot. They stay visible\nwhile the panel is hidden; each occupant includes text that names it for\nassistive technology, which becomes part of the toggle\'s name.', + registerOptions: [ + { + name: 'id', + requirement: 'required', + type: 'string', + doc: 'Your cell key. Use an id of your own: a fresh id is added beside the shipped entries, while reusing a shipped id puts you in THAT cell and replaces it. Owners that filter by id address you by it.', + }, + { + name: 'order', + requirement: 'optional', + type: 'number', + doc: 'Position among the entries, ascending (default 0).', + }, + { + name: 'label', + requirement: 'optional', + type: 'string | (() => string)', + doc: 'Display text where the owner projects one (nav rows, tabs). A thunk is re-read on every projection, so localized text follows the active locale without re-registering.', + }, + ], + ownerProps: [], + ownerPropsReferences: [], + standardProps: [ + 'useRemoteAccess: (action: RemoteEndpoint) => boolean', + 'useResource: UseResource', + 'useContextMenu: UseContextMenu', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessions: UseSessions', + 'useSessionStatus: UseSessionStatus', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', + 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', + 'useChat: UseChat', + 'useConversation: UseConversation', + 'useInput: SnapshotSelectorHook', + 'inputActions: InputActions', + 'useSession: SessionSnapshotSelector', + 'sessionId: SessionId', + 'useProjection: UseProjection', + 'useAccess: (action: RemoteEndpoint) => boolean', + 'useTrajectory: UseTrajectory', + ], + keyDomain: '', + hookContext: '', + slotInject: '', + declaredBy: 'an entry in \'conversation.session.header.utilities\' (client-ui-session-panel), so it exists while that entry is mounted', + occupants: [], + replaceRisk: 'none', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.panel.indicator\', () => ctx.slots.register(\n { name: \'conversation.session.panel.indicator\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/client/ui-session-panel/src/client/slots.ts:33', + }, + { + key: 'conversation.session.panel.section', + kind: 'list', + scope: 'session', + summary: 'Sections of the Session panel.', + doc: 'Sections of the Session panel. `id` addresses the section, `order` sorts\nthe sections ascending, and the required `label` is the section title,\nwhich the panel draws. A section with nothing to show renders nothing,\nand the panel hides its title with it.', + registerOptions: [ + { + name: 'id', + requirement: 'required', + type: 'string', + doc: 'Your cell key. Use an id of your own: a fresh id is added beside the shipped entries, while reusing a shipped id puts you in THAT cell and replaces it. Owners that filter by id address you by it.', + }, + { + name: 'order', + requirement: 'optional', + type: 'number', + doc: 'Position among the entries, ascending (default 0).', + }, + { + name: 'label', + requirement: 'optional', + type: 'string | (() => string)', + doc: 'Display text where the owner projects one (nav rows, tabs). A thunk is re-read on every projection, so localized text follows the active locale without re-registering.', + }, + ], + ownerProps: [ + '/** Values every section receives from the panel. */\nexport interface SessionPanelSectionOwnerProps {\n /** Current presentation; sections may lower their density in the overlay. */\n readonly presentation: SessionPanelPresentation\n /** Close the overlay, for example after a row opened another surface; no effect while docked. */\n readonly dismissOverlay: () => void\n}', + ], + ownerPropsReferences: [ + 'SessionPanelPresentation', + ], + standardProps: [ + 'useRemoteAccess: (action: RemoteEndpoint) => boolean', + 'useResource: UseResource', + 'useContextMenu: UseContextMenu', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessions: UseSessions', + 'useSessionStatus: UseSessionStatus', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', + 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', + 'useChat: UseChat', + 'useConversation: UseConversation', + 'useInput: SnapshotSelectorHook', + 'inputActions: InputActions', + 'useSession: SessionSnapshotSelector', + 'sessionId: SessionId', + 'useProjection: UseProjection', + 'useAccess: (action: RemoteEndpoint) => boolean', + 'useTrajectory: UseTrajectory', + ], + keyDomain: '', + hookContext: '', + slotInject: '', + declaredBy: 'an entry in \'conversation.session.panel\' (client-ui-session-panel), so it exists while that entry is mounted', + occupants: [ + 'client-ui-session-panel EnvironmentSection id \'environment\'', + ], + replaceRisk: 'none', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.panel.section\', () => ctx.slots.register(\n { name: \'conversation.session.panel.section\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/client/ui-session-panel/src/client/slots.ts:21', + }, + { + key: 'conversation.session.panel.section.actions', + kind: 'keyed', + scope: 'session', + summary: 'Trailing controls of one section title, keyed by the section\'s `id`.', + doc: 'Trailing controls of one section title, keyed by the section\'s `id`.', + registerOptions: [ + { + name: 'key', + requirement: 'required', + type: 'string', + doc: 'Your cell key: the entry renders where the owner dispatches this exact key. Registering an already-occupied key replaces that occupant.', + }, + ], + ownerProps: [], + ownerPropsReferences: [], + standardProps: [ + 'useRemoteAccess: (action: RemoteEndpoint) => boolean', + 'useResource: UseResource', + 'useContextMenu: UseContextMenu', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessions: UseSessions', + 'useSessionStatus: UseSessionStatus', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', + 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', + 'useChat: UseChat', + 'useConversation: UseConversation', + 'useInput: SnapshotSelectorHook', + 'inputActions: InputActions', + 'useSession: SessionSnapshotSelector', + 'sessionId: SessionId', + 'useProjection: UseProjection', + 'useAccess: (action: RemoteEndpoint) => boolean', + 'useTrajectory: UseTrajectory', + ], + keyDomain: 'open: any string the owner dispatches (no compile-time key set), none are taken yet', + hookContext: '', + slotInject: '', + declaredBy: 'an entry in \'conversation.session.panel\' (client-ui-session-panel), so it exists while that entry is mounted', + occupants: [], + replaceRisk: 'none', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.panel.section.actions\', () => ctx.slots.register(\n { name: \'conversation.session.panel.section.actions\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/client/ui-session-panel/src/client/slots.ts:27', }, { key: 'conversation.trajectory.images', @@ -2457,7 +2729,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.view\', () => ctx.slots.register(\n { name: \'conversation.view\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:285', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:292', }, { key: 'deliverables.file.actions', diff --git a/packages/preset/agent-preset/skills/cordis-composition-reference/references/packages.md b/packages/preset/agent-preset/skills/cordis-composition-reference/references/packages.md index 238deeaa99..d74b78bf35 100644 --- a/packages/preset/agent-preset/skills/cordis-composition-reference/references/packages.md +++ b/packages/preset/agent-preset/skills/cordis-composition-reference/references/packages.md @@ -98,6 +98,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo | `@deepseek-ai/dsh-client-ui-schedule` | no | Host task management page and Session reminder catalog | | `@deepseek-ai/dsh-client-ui-secret-mask` | no | Web display masking for recognized credentials in sent user text | | `@deepseek-ai/dsh-client-ui-session` | no | Session Controller adapter for React and session-scoped slots | +| `@deepseek-ai/dsh-client-ui-session-panel` | no | Floating Session panel opened from the Session header, composed of sections that plugins register | | `@deepseek-ai/dsh-client-ui-settings` | no | Settings domain base plugin: shared configuration forms and the canonical settings slot-type contract | | `@deepseek-ai/dsh-client-ui-settings-account` | yes | Manage DeepSeek login and open Platform billing pages | | `@deepseek-ai/dsh-client-ui-settings-agent-loop` | no | Settings page of the agent loop on the dsh web client's Plugins page: the parallel tool-call cap of the agent-loop namespace | diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f4ac595dde..d38a4c3c8d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3080,6 +3080,9 @@ importers: '@deepseek-ai/dsh-client-ui-session': specifier: workspace:* version: link:../../client/ui-session + '@deepseek-ai/dsh-client-ui-session-panel': + specifier: workspace:* + version: link:../../client/ui-session-panel '@deepseek-ai/dsh-client-ui-settings': specifier: workspace:* version: link:../../client/ui-settings @@ -5651,6 +5654,69 @@ importers: specifier: ^18.2.0 version: 18.3.1 + packages/client/ui-session-panel: + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-api-remotes': + specifier: workspace:* + version: link:../../api/remotes + '@deepseek-ai/dsh-api-session-controller': + specifier: workspace:* + version: link:../../api/session-controller + '@deepseek-ai/dsh-api-workspace-controller': + specifier: workspace:* + version: link:../../api/workspace-controller + '@deepseek-ai/dsh-client-locale': + specifier: workspace:* + version: link:../locale + '@deepseek-ai/dsh-client-store': + specifier: workspace:* + version: link:../store + '@deepseek-ai/dsh-client-test-runtime': + specifier: workspace:* + version: link:../../test-support/client-runtime + '@deepseek-ai/dsh-client-ui-context-menu': + specifier: workspace:* + version: link:../ui-context-menu + '@deepseek-ai/dsh-client-ui-conversation': + specifier: workspace:* + version: link:../ui-conversation + '@deepseek-ai/dsh-client-ui-primitives': + specifier: workspace:* + version: link:../ui-primitives + '@deepseek-ai/dsh-client-ui-renderer': + specifier: workspace:* + version: link:../ui-renderer + '@deepseek-ai/dsh-client-ui-session': + specifier: workspace:* + version: link:../ui-session + '@deepseek-ai/dsh-client-ui-slots': + specifier: workspace:* + version: link:../ui-slots + '@deepseek-ai/dsh-session': + specifier: workspace:* + version: link:../../core/session + '@deepseek-ai/dsh-util-workspace-path': + specifier: workspace:* + version: link:../../util/workspace-path + '@deepseek-ai/dsh-workspace': + specifier: workspace:* + version: link:../../workspace/workspace + '@testing-library/react': + specifier: ^16.3.3 + version: 16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + clsx: + specifier: ^2.0.0 + version: 2.1.1 + react: + specifier: ^18.2.0 + version: 18.3.1 + react-dom: + specifier: ^18.2.0 + version: 18.3.1(react@18.3.1) + packages/client/ui-settings: dependencies: '@deepseek-ai/schemastery': diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index 6e44649447..a61842d496 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -96,6 +96,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/attachment/attachment-local': { kind: 'indirect', reason: 'The local backend delegates model request rendering to provider adapters.' }, 'packages/mcp/mcp-manager': { kind: 'indirect', reason: 'The manager only mounts and disposes dsh-mcp-client instances; those instances own every model-facing tool and schema.' }, 'packages/client/ui-jobs': { kind: 'none', reason: 'Browser-side presentation of host-observed output; touches no prompt, message, schema, stream, or tool result.' }, + 'packages/client/ui-session-panel': { kind: 'none', reason: 'Browser-side summary of Session facts the Client already holds; touches no prompt, message, schema, stream, or tool result.' }, 'packages/shell/shell': { kind: 'indirect', reason: 'The service interface delegates all model rendering to dsh-tool-bash.' }, 'packages/shell/shell-env': { kind: 'indirect', reason: 'The env service exposes managed DSH_* facts through the shell tools (dsh-tool-bash/dsh-tool-pwsh); it registers no prompt or schema of its own.' }, 'packages/shell/bash-local': { kind: 'indirect', reason: 'The executor backend delegates model rendering to dsh-tool-bash.' }, diff --git a/tsconfig.base.json b/tsconfig.base.json index e130ee2d64..6964ee6bed 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -343,6 +343,8 @@ "@deepseek-ai/dsh-client-ui-jobs/client": ["./packages/client/ui-jobs/src/client/index.ts"], "@deepseek-ai/dsh-client-ui-schedule": ["./packages/client/ui-schedule/src"], "@deepseek-ai/dsh-client-ui-schedule/client": ["./packages/client/ui-schedule/src/client/index.ts"], + "@deepseek-ai/dsh-client-ui-session-panel": ["./packages/client/ui-session-panel/src"], + "@deepseek-ai/dsh-client-ui-session-panel/client": ["./packages/client/ui-session-panel/src/client/index.ts"], "@deepseek-ai/dsh-client-ui-plan": ["./packages/client/ui-plan/src"], "@deepseek-ai/dsh-client-ui-user-questions": ["./packages/client/ui-user-questions/src"], "@deepseek-ai/dsh-client-ui-trajectory": ["./packages/client/ui-trajectory/src"], diff --git a/tsconfig.client.json b/tsconfig.client.json index 0075d223e4..e0c16aaf5f 100644 --- a/tsconfig.client.json +++ b/tsconfig.client.json @@ -137,6 +137,7 @@ { "path": "./packages/client/ui-sidebar-files" }, { "path": "./packages/client/ui-jobs" }, { "path": "./packages/client/ui-schedule" }, + { "path": "./packages/client/ui-session-panel" }, { "path": "./packages/client/ui-directory-picker-browse" }, { "path": "./packages/client/ui-directory-picker-native" }, { "path": "./packages/client/ui-goal" }, From 3e6916a2d3d62318185fffb8dfc6088bcc9d4928 Mon Sep 17 00:00:00 2001 From: winewill Date: Thu, 5 Nov 2026 17:24:15 +0800 Subject: [PATCH 006/450] refactor(desktop): isolate publisher workspace for lightweight rollout --- .github/workflows/desktop-publish.yml | 8 ++-- .github/workflows/desktop-publisher-check.yml | 35 +++++++++++++++++ .github/workflows/desktop-rollout.yml | 37 +++++++++--------- apps/desktop-publisher/package.json | 19 ++++++++++ .../src}/cos-operation.ts | 0 .../desktop-auto-update-environment.d.mts | 0 .../src}/desktop-auto-update-environment.mjs | 0 .../src}/desktop-cos.ts | 2 +- .../src}/desktop-publication-failure.ts | 0 .../src}/desktop-publish-config.ts | 0 .../src}/desktop-publish-cos.ts | 5 ++- .../src}/desktop-publish-qualification.d.mts | 0 .../src}/desktop-publish-qualification.mjs | 0 .../src}/desktop-publish-record.ts | 2 +- .../src}/desktop-publish-route.ts | 0 .../src}/desktop-publish-targets.ts | 0 .../src}/desktop-publish.ts | 7 ++-- .../src}/desktop-purge-recovery.ts | 10 ++--- .../src/desktop-purge-types.ts | 7 ++++ .../src}/desktop-release-store.ts | 2 +- .../src/desktop-releases-root.ts | 15 ++++++++ .../src}/desktop-rollout.ts | 17 +++++---- .../src/desktop-upload-types.ts | 38 +++++++++++++++++++ .../src}/desktop-website-installer.ts | 8 ++-- .../src}/publish-desktop-rollout-ci.ts | 4 +- .../src}/publish-website-ci.ts | 6 +-- .../src}/resolve-desktop-publish-ci.ts | 6 +-- .../resolve-retained-desktop-publish-ci.ts | 6 +-- .../tests/cos-loopback.ts | 0 .../tests/cos-operation.spec.ts | 4 +- .../desktop-auto-update-environment.spec.ts | 2 +- .../tests/desktop-package-selection.spec.ts | 6 +-- .../tests/desktop-publication-failure.spec.ts | 10 ++--- .../tests/desktop-publish-config.spec.ts | 2 +- .../tests/desktop-publish-cos.spec.ts | 10 ++--- .../tests/desktop-publish-record.spec.ts | 4 +- .../tests/desktop-publish-route.spec.ts | 2 +- .../tests/desktop-publish.spec.ts | 4 +- .../tests/desktop-purge-recovery.spec.ts | 4 +- .../tests/desktop-release-store.spec.ts | 2 +- .../tests/desktop-website-installer.spec.ts | 10 ++--- .../tests/expected/cos-GetObject-denied.json | 0 .../tests/expected/cos-PutObject-denied.json | 0 .../tests/expected/website-purge-accepted.md | 0 .../expected/website-purge-unconfirmed.md | 0 .../tests/isolated-install.mjs | 18 +++++++++ .../tests/publish-website-ci.spec.ts | 4 +- apps/desktop-publisher/tests/workflow.spec.ts | 31 +++++++++++++++ apps/desktop/package.json | 3 +- apps/desktop/scripts/archive-desktop-ci.ts | 4 +- .../desktop/scripts/desktop-build-paths.d.mts | 2 +- .../desktop-build-version-discovery.ts | 4 +- apps/desktop/scripts/desktop-edgeone.ts | 11 ++---- .../scripts/desktop-package-environment.mjs | 2 +- .../scripts/desktop-policy-environment.mjs | 2 +- .../scripts/desktop-publication-summary.ts | 4 +- apps/desktop/scripts/desktop-rollback.ts | 2 +- apps/desktop/scripts/desktop-upload-plan.ts | 33 ++-------------- apps/desktop/scripts/desktop-upload-run.ts | 6 ++- apps/desktop/scripts/development-project.ts | 2 +- .../scripts/electron-builder-config.mjs | 2 +- apps/desktop/scripts/installed-update-cos.ts | 4 +- .../scripts/macos-app-update-config.mjs | 2 +- apps/desktop/scripts/package-macos.ts | 2 +- apps/desktop/scripts/package-target.ts | 2 +- .../scripts/preflight-desktop-publish.mjs | 2 +- apps/desktop/scripts/publish-desktop-ci.ts | 16 ++++---- apps/desktop/scripts/retain-desktop-ci.ts | 23 ++++------- .../scripts/rollback-desktop-channel.ts | 8 ++-- apps/desktop/scripts/upload-target.ts | 4 +- .../scripts/verify-retained-desktop.ts | 4 +- .../tests/desktop-publication-summary.spec.ts | 2 +- .../tests/desktop-publish-templates.spec.ts | 2 +- apps/desktop/tests/desktop-rollback.spec.ts | 2 +- apps/desktop/tests/desktop-rollout.spec.ts | 22 +++++------ .../desktop/tests/desktop-upload-plan.spec.ts | 6 +-- apps/desktop/tests/desktop-upload-run.spec.ts | 6 +-- .../tests/installed-update-cos.spec.ts | 6 +-- apps/desktop/tests/purge-command.spec.ts | 4 +- apps/desktop/tests/retain-desktop-ci.spec.ts | 2 +- apps/desktop/tests/upload-target.spec.ts | 2 +- pnpm-lock.yaml | 24 ++++++++++++ scripts/check-workspace-constraints.spec.ts | 3 +- scripts/check-workspace-constraints.ts | 6 ++- scripts/desktop-publish-workflow.spec.ts | 4 +- tsconfig.base.json | 1 + tsconfig.host.json | 2 + 87 files changed, 372 insertions(+), 213 deletions(-) create mode 100644 .github/workflows/desktop-publisher-check.yml create mode 100644 apps/desktop-publisher/package.json rename apps/{desktop/scripts => desktop-publisher/src}/cos-operation.ts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-auto-update-environment.d.mts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-auto-update-environment.mjs (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-cos.ts (97%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publication-failure.ts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish-config.ts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish-cos.ts (95%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish-qualification.d.mts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish-qualification.mjs (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish-record.ts (99%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish-route.ts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish-targets.ts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish.ts (96%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-purge-recovery.ts (94%) create mode 100644 apps/desktop-publisher/src/desktop-purge-types.ts rename apps/{desktop/scripts => desktop-publisher/src}/desktop-release-store.ts (98%) create mode 100644 apps/desktop-publisher/src/desktop-releases-root.ts rename apps/{desktop/scripts => desktop-publisher/src}/desktop-rollout.ts (92%) create mode 100644 apps/desktop-publisher/src/desktop-upload-types.ts rename apps/{desktop/scripts => desktop-publisher/src}/desktop-website-installer.ts (97%) rename apps/{desktop/scripts => desktop-publisher/src}/publish-desktop-rollout-ci.ts (98%) rename apps/{desktop/scripts => desktop-publisher/src}/publish-website-ci.ts (97%) rename apps/{desktop/scripts => desktop-publisher/src}/resolve-desktop-publish-ci.ts (95%) rename apps/{desktop/scripts => desktop-publisher/src}/resolve-retained-desktop-publish-ci.ts (95%) rename apps/{desktop => desktop-publisher}/tests/cos-loopback.ts (100%) rename apps/{desktop => desktop-publisher}/tests/cos-operation.spec.ts (96%) rename apps/{desktop => desktop-publisher}/tests/desktop-auto-update-environment.spec.ts (98%) rename apps/{desktop => desktop-publisher}/tests/desktop-package-selection.spec.ts (97%) rename apps/{desktop => desktop-publisher}/tests/desktop-publication-failure.spec.ts (89%) rename apps/{desktop => desktop-publisher}/tests/desktop-publish-config.spec.ts (97%) rename apps/{desktop => desktop-publisher}/tests/desktop-publish-cos.spec.ts (91%) rename apps/{desktop => desktop-publisher}/tests/desktop-publish-record.spec.ts (96%) rename apps/{desktop => desktop-publisher}/tests/desktop-publish-route.spec.ts (98%) rename apps/{desktop => desktop-publisher}/tests/desktop-publish.spec.ts (97%) rename apps/{desktop => desktop-publisher}/tests/desktop-purge-recovery.spec.ts (97%) rename apps/{desktop => desktop-publisher}/tests/desktop-release-store.spec.ts (97%) rename apps/{desktop => desktop-publisher}/tests/desktop-website-installer.spec.ts (94%) rename apps/{desktop => desktop-publisher}/tests/expected/cos-GetObject-denied.json (100%) rename apps/{desktop => desktop-publisher}/tests/expected/cos-PutObject-denied.json (100%) rename apps/{desktop => desktop-publisher}/tests/expected/website-purge-accepted.md (100%) rename apps/{desktop => desktop-publisher}/tests/expected/website-purge-unconfirmed.md (100%) create mode 100644 apps/desktop-publisher/tests/isolated-install.mjs rename apps/{desktop => desktop-publisher}/tests/publish-website-ci.spec.ts (97%) create mode 100644 apps/desktop-publisher/tests/workflow.spec.ts diff --git a/.github/workflows/desktop-publish.yml b/.github/workflows/desktop-publish.yml index 32efedf65c..8a1fa4d79d 100644 --- a/.github/workflows/desktop-publish.yml +++ b/.github/workflows/desktop-publish.yml @@ -57,7 +57,7 @@ jobs: GH_TOKEN: ${{ github.token }} DESKTOP_PUBLISH_RUNNERS: ${{ vars.DESKTOP_PUBLISH_RUNNERS }} DESKTOP_PACKAGE_ATTEMPT: ${{ steps.preflight.outputs.attempt }} - run: node --import tsx apps/desktop/scripts/resolve-desktop-publish-ci.ts + run: node --import tsx apps/desktop-publisher/src/resolve-desktop-publish-ci.ts prepare: needs: route @@ -99,7 +99,7 @@ jobs: working-directory: desktop-publisher env: GH_TOKEN: ${{ github.token }} - run: node --import tsx apps/desktop/scripts/resolve-retained-desktop-publish-ci.ts + run: node --import tsx apps/desktop-publisher/src/resolve-retained-desktop-publish-ci.ts - name: Verify local package without upload credentials id: check working-directory: desktop-publisher @@ -210,7 +210,7 @@ jobs: - name: Upload website installer id: website working-directory: website-publisher - run: node --import tsx apps/desktop/scripts/publish-website-ci.ts upload + run: node --import tsx apps/desktop-publisher/src/publish-website-ci.ts upload - name: Archive website publication diagnostics if: always() && steps.website.outputs.record != '' continue-on-error: true @@ -255,7 +255,7 @@ jobs: - name: Recover and observe website cache purge id: website working-directory: website-publisher - run: node --import tsx apps/desktop/scripts/publish-website-ci.ts purge + run: node --import tsx apps/desktop-publisher/src/publish-website-ci.ts purge - name: Archive website publication diagnostics if: always() && steps.website.outputs.record != '' continue-on-error: true diff --git a/.github/workflows/desktop-publisher-check.yml b/.github/workflows/desktop-publisher-check.yml new file mode 100644 index 0000000000..37ad3220d2 --- /dev/null +++ b/.github/workflows/desktop-publisher-check.yml @@ -0,0 +1,35 @@ +name: Verify Desktop Publisher +on: + pull_request: + paths: + - 'apps/desktop-publisher/**' + - 'apps/desktop/**' + - 'package.json' + - 'pnpm-lock.yaml' + - 'pnpm-workspace.yaml' + - '.github/workflows/desktop-publisher-check.yml' + - '.github/workflows/desktop-rollout.yml' + workflow_dispatch: +permissions: + contents: read +jobs: + isolated-install: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - uses: pnpm/action-setup@v5.0.0 + - uses: actions/setup-node@v7.0.0 + with: + node-version: '24' + - name: Install only publisher production dependencies + run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts + - name: Load publisher without the Desktop or root development dependencies + working-directory: apps/desktop-publisher + run: node --import tsx tests/isolated-install.mjs diff --git a/.github/workflows/desktop-rollout.yml b/.github/workflows/desktop-rollout.yml index 13549da6b4..80932b63f2 100644 --- a/.github/workflows/desktop-rollout.yml +++ b/.github/workflows/desktop-rollout.yml @@ -50,14 +50,15 @@ jobs: - uses: actions/setup-node@v7.0.0 with: node-version: '24' - - run: pnpm install --frozen-lockfile + - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts - name: Resolve original package and machine id: route env: GH_TOKEN: ${{ github.token }} DESKTOP_PUBLISH_RUNNERS: ${{ vars.DESKTOP_PUBLISH_RUNNERS }} DESKTOP_PACKAGE_ATTEMPT: ${{ steps.preflight.outputs.attempt }} - run: node --import tsx apps/desktop/scripts/resolve-desktop-publish-ci.ts + working-directory: apps/desktop-publisher + run: node --import tsx src/resolve-desktop-publish-ci.ts prepare: needs: route @@ -92,20 +93,20 @@ jobs: - name: Check local publication configuration before dependency installation working-directory: desktop-publisher run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs - - run: pnpm install --frozen-lockfile + - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts working-directory: desktop-publisher - name: Resolve retained package and approval environment id: local - working-directory: desktop-publisher + working-directory: desktop-publisher/apps/desktop-publisher env: GH_TOKEN: ${{ github.token }} - run: node --import tsx apps/desktop/scripts/publish-desktop-rollout-ci.ts route + run: node --import tsx src/publish-desktop-rollout-ci.ts route - name: Verify initial publication and metadata without upload credentials id: check - working-directory: desktop-publisher + working-directory: desktop-publisher/apps/desktop-publisher env: DESKTOP_PUBLISH_ROUTE: ${{ steps.local.outputs.route }} - run: node --import tsx apps/desktop/scripts/publish-desktop-rollout-ci.ts check + run: node --import tsx src/publish-desktop-rollout-ci.ts check publish: name: Approve ${{ needs.prepare.outputs.label }} @@ -139,16 +140,16 @@ jobs: - name: Check local publication configuration before dependency installation working-directory: desktop-publisher run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs - - run: pnpm install --frozen-lockfile + - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts working-directory: desktop-publisher - name: Verify initial publication and metadata without upload credentials id: check - working-directory: desktop-publisher - run: node --import tsx apps/desktop/scripts/publish-desktop-rollout-ci.ts check + working-directory: desktop-publisher/apps/desktop-publisher + run: node --import tsx src/publish-desktop-rollout-ci.ts check - name: Apply rollout to the published feed id: publish - working-directory: desktop-publisher - run: node --import tsx apps/desktop/scripts/publish-desktop-rollout-ci.ts apply + working-directory: desktop-publisher/apps/desktop-publisher + run: node --import tsx src/publish-desktop-rollout-ci.ts apply - name: Retain publication audit continue-on-error: true if: always() && steps.publish.outputs.record != '' @@ -191,12 +192,12 @@ jobs: - name: Check local publication configuration working-directory: website-publisher run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs - - run: pnpm install --frozen-lockfile + - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts working-directory: website-publisher - name: Upload website installer id: website - working-directory: website-publisher - run: node --import tsx apps/desktop/scripts/publish-desktop-rollout-ci.ts website-upload + working-directory: website-publisher/apps/desktop-publisher + run: node --import tsx src/publish-desktop-rollout-ci.ts website-upload - name: Archive website feed verification if: always() && steps.website.outputs.rollout-record != '' continue-on-error: true @@ -246,12 +247,12 @@ jobs: - name: Check local publication configuration working-directory: website-publisher run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs - - run: pnpm install --frozen-lockfile + - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts working-directory: website-publisher - name: Recover and observe website cache purge id: website - working-directory: website-publisher - run: node --import tsx apps/desktop/scripts/publish-desktop-rollout-ci.ts website-purge + working-directory: website-publisher/apps/desktop-publisher + run: node --import tsx src/publish-desktop-rollout-ci.ts website-purge - name: Archive website publication diagnostics if: always() && steps.website.outputs.record != '' continue-on-error: true diff --git a/apps/desktop-publisher/package.json b/apps/desktop-publisher/package.json new file mode 100644 index 0000000000..c8aaf573f7 --- /dev/null +++ b/apps/desktop-publisher/package.json @@ -0,0 +1,19 @@ +{ + "name": "@deepseek-ai/dsh-desktop-publisher", + "version": "0.2.2-rc.1", + "description": "Private Desktop release metadata, rollout and website publisher", + "private": true, + "type": "module", + "license": "MIT", + "exports": { + "./*": "./src/*" + }, + "dependencies": { + "zod": "4.6.6", + "js-yaml": "^4.3.2", + "semver": "^7.8.5", + "cos-nodejs-sdk-v5": "3.0.0", + "tencentcloud-sdk-nodejs-teo": "4.1.330", + "tsx": "^4.23.13" + } +} diff --git a/apps/desktop/scripts/cos-operation.ts b/apps/desktop-publisher/src/cos-operation.ts similarity index 100% rename from apps/desktop/scripts/cos-operation.ts rename to apps/desktop-publisher/src/cos-operation.ts diff --git a/apps/desktop/scripts/desktop-auto-update-environment.d.mts b/apps/desktop-publisher/src/desktop-auto-update-environment.d.mts similarity index 100% rename from apps/desktop/scripts/desktop-auto-update-environment.d.mts rename to apps/desktop-publisher/src/desktop-auto-update-environment.d.mts diff --git a/apps/desktop/scripts/desktop-auto-update-environment.mjs b/apps/desktop-publisher/src/desktop-auto-update-environment.mjs similarity index 100% rename from apps/desktop/scripts/desktop-auto-update-environment.mjs rename to apps/desktop-publisher/src/desktop-auto-update-environment.mjs diff --git a/apps/desktop/scripts/desktop-cos.ts b/apps/desktop-publisher/src/desktop-cos.ts similarity index 97% rename from apps/desktop/scripts/desktop-cos.ts rename to apps/desktop-publisher/src/desktop-cos.ts index 6074d84a05..a117cec4ff 100644 --- a/apps/desktop/scripts/desktop-cos.ts +++ b/apps/desktop-publisher/src/desktop-cos.ts @@ -47,7 +47,7 @@ export function createDesktopCos(credentials: DesktopCosCredentials, timeoutMs: }) cos.on('before-send', (options: CosRequestOptions) => { for (const name of Object.keys(options.headers)) { - if (name.toLowerCase() === 'cache-control' && options.headers[name] === '') delete options.headers[name] + if (name.toLowerCase() === 'cache-control' && options.headers[name] === '') Reflect.deleteProperty(options.headers, name) } }) return cos diff --git a/apps/desktop/scripts/desktop-publication-failure.ts b/apps/desktop-publisher/src/desktop-publication-failure.ts similarity index 100% rename from apps/desktop/scripts/desktop-publication-failure.ts rename to apps/desktop-publisher/src/desktop-publication-failure.ts diff --git a/apps/desktop/scripts/desktop-publish-config.ts b/apps/desktop-publisher/src/desktop-publish-config.ts similarity index 100% rename from apps/desktop/scripts/desktop-publish-config.ts rename to apps/desktop-publisher/src/desktop-publish-config.ts diff --git a/apps/desktop/scripts/desktop-publish-cos.ts b/apps/desktop-publisher/src/desktop-publish-cos.ts similarity index 95% rename from apps/desktop/scripts/desktop-publish-cos.ts rename to apps/desktop-publisher/src/desktop-publish-cos.ts index 086303238e..cb89baada6 100644 --- a/apps/desktop/scripts/desktop-publish-cos.ts +++ b/apps/desktop-publisher/src/desktop-publish-cos.ts @@ -5,7 +5,7 @@ import { Readable, Writable } from 'node:stream' import type COS from 'cos-nodejs-sdk-v5' import { createDesktopCos, DESKTOP_COS_REGION, type DesktopCosCredentials } from './desktop-cos.ts' import { cosOperation } from './cos-operation.ts' -import type { DesktopUploadPlan } from './desktop-upload-plan.ts' +import type { DesktopUploadPlan } from './desktop-upload-types.ts' import { desktopArtifactDigest, type DesktopPublishTransport } from './desktop-publish.ts' import { DesktopCosOperationError } from './desktop-publication-failure.ts' @@ -66,7 +66,8 @@ export function desktopPublishCos( if (actual.size !== digest.size || actual.sha512 !== digest.sha512) throw new Error('desktop publish: local input changed') const cos = client() const md5 = createHash('md5') - const bytes = artifact.contents === undefined ? createReadStream(artifact.path) : [Buffer.from(artifact.contents)] + const bytes = artifact.contents === undefined + ? createReadStream(artifact.path) as AsyncIterable : [Buffer.from(artifact.contents)] for await (const chunk of bytes) md5.update(chunk) const body = artifact.contents === undefined ? createReadStream(artifact.path) : Readable.from([Buffer.from(artifact.contents)]) try { diff --git a/apps/desktop/scripts/desktop-publish-qualification.d.mts b/apps/desktop-publisher/src/desktop-publish-qualification.d.mts similarity index 100% rename from apps/desktop/scripts/desktop-publish-qualification.d.mts rename to apps/desktop-publisher/src/desktop-publish-qualification.d.mts diff --git a/apps/desktop/scripts/desktop-publish-qualification.mjs b/apps/desktop-publisher/src/desktop-publish-qualification.mjs similarity index 100% rename from apps/desktop/scripts/desktop-publish-qualification.mjs rename to apps/desktop-publisher/src/desktop-publish-qualification.mjs diff --git a/apps/desktop/scripts/desktop-publish-record.ts b/apps/desktop-publisher/src/desktop-publish-record.ts similarity index 99% rename from apps/desktop/scripts/desktop-publish-record.ts rename to apps/desktop-publisher/src/desktop-publish-record.ts index 718146b86b..6e1fdd554b 100644 --- a/apps/desktop/scripts/desktop-publish-record.ts +++ b/apps/desktop-publisher/src/desktop-publish-record.ts @@ -108,7 +108,7 @@ export async function findDesktopPublication(root: string, expected: { for (const entry of entries) { if (!entry.isDirectory() || !entry.name.startsWith('publish-')) continue const directory = join(root, entry.name) - let operation + let operation: unknown try { operation = JSON.parse(await readFile(join(directory, 'operation.json'), 'utf8')) } catch (error) { if (error instanceof Error && 'code' in error && error.code === 'ENOENT') continue throw error diff --git a/apps/desktop/scripts/desktop-publish-route.ts b/apps/desktop-publisher/src/desktop-publish-route.ts similarity index 100% rename from apps/desktop/scripts/desktop-publish-route.ts rename to apps/desktop-publisher/src/desktop-publish-route.ts diff --git a/apps/desktop/scripts/desktop-publish-targets.ts b/apps/desktop-publisher/src/desktop-publish-targets.ts similarity index 100% rename from apps/desktop/scripts/desktop-publish-targets.ts rename to apps/desktop-publisher/src/desktop-publish-targets.ts diff --git a/apps/desktop/scripts/desktop-publish.ts b/apps/desktop-publisher/src/desktop-publish.ts similarity index 96% rename from apps/desktop/scripts/desktop-publish.ts rename to apps/desktop-publisher/src/desktop-publish.ts index d11e2bd098..eb0f2a4ab6 100644 --- a/apps/desktop/scripts/desktop-publish.ts +++ b/apps/desktop-publisher/src/desktop-publish.ts @@ -4,7 +4,7 @@ import { createReadStream } from 'node:fs' import { load } from 'js-yaml' import { gt, valid } from 'semver' import { z } from 'zod' -import type { DesktopUploadArtifact, DesktopUploadPlan } from './desktop-upload-plan.ts' +import type { DesktopUploadArtifact, DesktopUploadPlan } from './desktop-upload-types.ts' /** File identity computed from bytes, never inferred from COS ETags. */ export interface DesktopObjectDigest { readonly size: number; readonly sha512: string } @@ -51,7 +51,8 @@ export class DesktopPublishError extends Error { export async function desktopArtifactDigest(artifact: DesktopUploadArtifact): Promise { const hash = createHash('sha512') let size = 0 - const stream = artifact.contents === undefined ? createReadStream(artifact.path) : [Buffer.from(artifact.contents)] + const stream = artifact.contents === undefined + ? createReadStream(artifact.path) as AsyncIterable : [Buffer.from(artifact.contents)] for await (const bytes of stream) { hash.update(bytes); size += bytes.length } return { size, sha512: hash.digest('base64') } } @@ -64,7 +65,7 @@ function version(contents: string, remote = false): string { try { const parsed = z.object({ version: z.string() }).parse(load(contents)) if (valid(parsed.version) !== null) return parsed.version - } catch (error) { /* Discard parser error details, which may include raw remote YAML. */ } + } catch (_error) { /* Discard parser error details, which may include raw remote YAML. */ } throw new DesktopPublishError(remote ? 'verification-failed' : 'invalid-plan', `desktop publish: invalid ${remote ? 'remote' : 'planned'} channel version`) } diff --git a/apps/desktop/scripts/desktop-purge-recovery.ts b/apps/desktop-publisher/src/desktop-purge-recovery.ts similarity index 94% rename from apps/desktop/scripts/desktop-purge-recovery.ts rename to apps/desktop-publisher/src/desktop-purge-recovery.ts index 890ea003ba..c23cac9ecf 100644 --- a/apps/desktop/scripts/desktop-purge-recovery.ts +++ b/apps/desktop-publisher/src/desktop-purge-recovery.ts @@ -1,6 +1,6 @@ /** Resume a fixed-URL purge without repeating ambiguous submissions. */ import type { teo } from 'tencentcloud-sdk-nodejs-teo' -import type { DesktopPurgeConfig } from './desktop-edgeone.ts' +import type { DesktopPurgeConfig } from './desktop-purge-types.ts' /** Non-secret evidence saved before submission and after every observation. */ export interface DesktopPurgeRecord { @@ -65,12 +65,12 @@ async function observe(record: DesktopPurgeRecord, client: DesktopPurgeRecoveryC if (offset >= response.TotalCount) break if (response.Tasks.length === 0 || offset >= 10_000) return unknown('task history could not be fully inspected') } while (true) - } catch (error) { return unknown('task query failed; check EdgeOne history and DescribePurgeTasks permission') } + } catch (_error) { return unknown('task query failed; check EdgeOne history and DescribePurgeTasks permission') } if (matches.length === 0) return unknown(record.jobId ? 'accepted task not found in query history; execution result unconfirmed' : 'no matching submission found; purge may not have been submitted; inspect EdgeOne history before manual recovery') - if (matches.length !== 1) return unknown('multiple matching submissions found; cannot identify this submission') - const task = matches[0]! + const task = matches[0] + if (matches.length !== 1 || !task) return unknown('multiple matching submissions found; cannot identify this submission') if (!task.JobId || !/^[\w.-]{1,128}$/u.test(task.JobId) || task.JobId.includes(config.secretId) || task.JobId.includes(config.secretKey)) return unknown('query returned no usable task ID') const status = task.Status @@ -115,7 +115,7 @@ export async function recoverDesktopPurge(config: DesktopPurgeConfig, previous: await options.save(record) let response: Awaited> | undefined try { response = await client.CreatePurgeTask({ ZoneId: config.zoneId, Type: 'purge_url', Targets: [config.publicUrl] }) } - catch (error) { /* Submission may have reached EdgeOne; reconcile history without repeating the request. */ } + catch (_error) { /* Submission may have reached EdgeOne; reconcile history without repeating the request. */ } const jobId = response?.JobId if (response?.FailedList?.length) { record = { ...record, status: 'failed' } diff --git a/apps/desktop-publisher/src/desktop-purge-types.ts b/apps/desktop-publisher/src/desktop-purge-types.ts new file mode 100644 index 0000000000..c55ec465ab --- /dev/null +++ b/apps/desktop-publisher/src/desktop-purge-types.ts @@ -0,0 +1,7 @@ +/** Validated production destination and credentials; never serialize this value. */ +export interface DesktopPurgeConfig { + readonly zoneId: string + readonly publicUrl: string + readonly secretId: string + readonly secretKey: string +} diff --git a/apps/desktop/scripts/desktop-release-store.ts b/apps/desktop-publisher/src/desktop-release-store.ts similarity index 98% rename from apps/desktop/scripts/desktop-release-store.ts rename to apps/desktop-publisher/src/desktop-release-store.ts index eb9d5457ff..ae7915443c 100644 --- a/apps/desktop/scripts/desktop-release-store.ts +++ b/apps/desktop-publisher/src/desktop-release-store.ts @@ -44,7 +44,7 @@ async function fingerprint(path: string) { if (!info.isFile() || info.isSymbolicLink()) throw new Error('desktop release store: expected a regular file') const hash = createHash('sha512') let size = 0 - for await (const bytes of createReadStream(path)) { size += bytes.length; hash.update(bytes) } + for await (const bytes of createReadStream(path) as AsyncIterable) { size += bytes.length; hash.update(bytes) } if (size === 0) throw new Error('desktop release store: empty artifact') return { size, sha512: hash.digest('base64') } } diff --git a/apps/desktop-publisher/src/desktop-releases-root.ts b/apps/desktop-publisher/src/desktop-releases-root.ts new file mode 100644 index 0000000000..3d7e11c141 --- /dev/null +++ b/apps/desktop-publisher/src/desktop-releases-root.ts @@ -0,0 +1,15 @@ +/** Resolve retained Desktop storage independently of packaging and signing. */ +import { dirname, isAbsolute, join } from 'node:path' + +/** + * Resolve the persistent release root without assuming a particular user's home directory. + * @param env Machine packaging configuration; an explicit releases directory overrides its sibling default. + * @returns Absolute directory outside the disposable checkout. + */ +export function desktopReleasesRoot(env: NodeJS.ProcessEnv): string { + const configured = env.DSH_PACKAGING_CONFIG_DIR + if (!configured) throw new Error('desktop retention: DSH_PACKAGING_CONFIG_DIR is required') + const root = env.DSH_DESKTOP_RELEASES_DIR || join(dirname(configured), 'releases') + if (!isAbsolute(configured) || !isAbsolute(root)) throw new Error('desktop retention: machine directories must be absolute') + return root +} diff --git a/apps/desktop/scripts/desktop-rollout.ts b/apps/desktop-publisher/src/desktop-rollout.ts similarity index 92% rename from apps/desktop/scripts/desktop-rollout.ts rename to apps/desktop-publisher/src/desktop-rollout.ts index 50750ef1e8..257830b1a3 100644 --- a/apps/desktop/scripts/desktop-rollout.ts +++ b/apps/desktop-publisher/src/desktop-rollout.ts @@ -7,15 +7,15 @@ import { dump, load } from 'js-yaml' import { z } from 'zod' import { desktopUpdateMetadataFilename, resolveDesktopUploadConfig } from './desktop-auto-update-environment.mjs' import type { DesktopRetainedManifest } from './desktop-release-store.ts' -import type { DesktopUploadPlan } from './desktop-upload-plan.ts' +import type { DesktopSingleUploadPlan } from './desktop-upload-types.ts' import { desktopArtifactDigest, type DesktopPublishOperations, type DesktopRemoteObject } from './desktop-publish.ts' const percentage = z.number().int().min(0).max(100) const metadataSchema = z.object({ version: z.string(), - files: z.array(z.object({ url: z.string(), size: z.number().int().positive(), sha512: z.string() }).passthrough()).length(1), + files: z.tuple([z.object({ url: z.string(), size: z.number().int().positive(), sha512: z.string() }).loose()]), path: z.string().optional(), sha512: z.string().optional(), stagingPercentage: percentage.optional(), -}).passthrough() +}).loose() function metadata(contents: string) { if (Buffer.byteLength(contents) > 1024 * 1024) throw new Error('desktop rollout: metadata exceeds 1 MiB') @@ -26,7 +26,7 @@ function metadata(contents: string) { /** Validated immutable update identity; no installer bytes are read. */ export interface DesktopRolloutPlan { - readonly upload: DesktopUploadPlan + readonly upload: DesktopSingleUploadPlan readonly expected: string } @@ -56,7 +56,7 @@ export async function prepareDesktopRollout(directory: string, manifest: Desktop const parsed = metadata(contents) const payload = `deepseek-harness-${source.version}-${source.target}.${windows ? 'exe' : 'zip'}` const file = manifest.files.find(entry => entry.name === payload) - const entry = parsed.files[0]! + const entry = parsed.files[0] if (parsed.version !== source.version || entry.url !== payload || !file || entry.size !== file.size || entry.sha512 !== file.sha512 || (parsed.path !== undefined && parsed.path !== payload) @@ -103,8 +103,9 @@ export function verifyDesktopRolloutFeed(plan: DesktopRolloutPlan, remote: Deskt export async function rolloutDesktopRelease(plan: DesktopRolloutPlan, target: number | undefined, operations: Pick) { if (target !== undefined) percentage.parse(target) - const artifact = plan.upload.artifacts[0]! + const artifact = plan.upload.artifacts[0] const before = await operations.transport.read(artifact.key, true) + if (!before?.contents) throw new Error('desktop rollout: published update feed is missing') const current = verifyDesktopRolloutFeed(plan, before) const next = target ?? current.percentage if (next < current.percentage) throw new Error('desktop rollout: percentage cannot decrease; inspect the current rollout') @@ -115,8 +116,8 @@ export async function rolloutDesktopRelease(plan: DesktopRolloutPlan, target: nu const updated = { ...artifact, contents: dump({ ...current.metadata, stagingPercentage: next }) } const digest = await desktopArtifactDigest(updated) const confirmed = await operations.transport.read(artifact.key, true) - if (confirmed?.contents !== before?.contents) throw new Error('desktop rollout: feed changed before write; inspect and retry') - await operations.record({ type: 'put-intent', key: artifact.key, before: before!.contents!, after: updated.contents }) + if (confirmed?.contents !== before.contents) throw new Error('desktop rollout: feed changed before write; inspect and retry') + await operations.record({ type: 'put-intent', key: artifact.key, before: before.contents, after: updated.contents }) await operations.transport.put(updated, digest, false) const actual = await operations.transport.read(artifact.key, true) if (actual?.size !== digest.size || actual.sha512 !== digest.sha512) { diff --git a/apps/desktop-publisher/src/desktop-upload-types.ts b/apps/desktop-publisher/src/desktop-upload-types.ts new file mode 100644 index 0000000000..4faa48b399 --- /dev/null +++ b/apps/desktop-publisher/src/desktop-upload-types.ts @@ -0,0 +1,38 @@ +/** Shared upload contracts for Desktop packaging and publication. */ +import type { DesktopAutoUpdateTarget } from './desktop-auto-update-environment.mjs' + +/** One local file and its final object metadata. */ +export interface DesktopUploadArtifact { + readonly path: string + readonly filename: string + readonly key: string + readonly contentType: string + /** Browser save name for fixed website downloads, preserving the validated installer basename. */ + readonly contentDisposition?: string + readonly channelMetadata: boolean + /** Published YAML with normalized artifact URLs; binary bytes remain file-backed. */ + readonly contents?: string +} + +/** A validated installer or update upload, with any channel metadata ordered last. */ +export interface DesktopUploadPlan { + readonly environment: 'test' | 'production' + readonly target: DesktopAutoUpdateTarget + readonly version: string + /** Update feed directory URL, or the single installer URL for a fixed download. */ + readonly publicUrl: string + readonly bucket: string + readonly secretIdEnvName: string + readonly secretKeyEnvName: string + readonly artifacts: readonly DesktopUploadArtifact[] + /** Commit the artifacts were packaged from, absent for a package built before builds recorded it. */ + readonly commit?: string + /** Whether that checkout carried uncommitted changes. */ + readonly dirty?: boolean +} + + +/** A publication operation targeting exactly one metadata object or installer. */ +export type DesktopSingleUploadPlan = Omit & { + readonly artifacts: readonly [DesktopUploadArtifact] +} diff --git a/apps/desktop/scripts/desktop-website-installer.ts b/apps/desktop-publisher/src/desktop-website-installer.ts similarity index 97% rename from apps/desktop/scripts/desktop-website-installer.ts rename to apps/desktop-publisher/src/desktop-website-installer.ts index 8e3838481f..f98cb20252 100644 --- a/apps/desktop/scripts/desktop-website-installer.ts +++ b/apps/desktop-publisher/src/desktop-website-installer.ts @@ -9,11 +9,11 @@ import { createDesktopCos, DESKTOP_COS_REGION, type DesktopCosCredentials } from import { cosOperation } from './cos-operation.ts' import type { DesktopObjectDigest, DesktopPublishTransport } from './desktop-publish.ts' import { DesktopCosOperationError } from './desktop-publication-failure.ts' -import type { DesktopUploadPlan } from './desktop-upload-plan.ts' +import type { DesktopSingleUploadPlan } from './desktop-upload-types.ts' /** Verified file and destination; the caller closes the handle after publication. */ export interface DesktopWebsiteInstaller { - readonly plan: DesktopUploadPlan + readonly plan: DesktopSingleUploadPlan readonly digest: DesktopObjectDigest readonly md5: string readonly contentDisposition: string @@ -52,7 +52,7 @@ export async function prepareWebsiteInstaller(directory: string, manifest: Deskt const sha512 = createHash('sha512') const md5 = createHash('md5') let size = 0 - for await (const bytes of handle.createReadStream({ autoClose: false, start: 0 })) { + for await (const bytes of handle.createReadStream({ autoClose: false, start: 0 }) as AsyncIterable) { size += bytes.length sha512.update(bytes) md5.update(bytes) @@ -89,7 +89,7 @@ export async function uploadWebsiteInstaller(installer: DesktopWebsiteInstaller, record: (event: 'upload-intent' | 'uploaded') => Promise, options: { createClient?: typeof createDesktopCos; previouslyUploaded?: boolean } = {}, ): Promise<'uploaded' | 'present'> { - const artifact = installer.plan.artifacts[0]! + const artifact = installer.plan.artifacts[0] const matches = (remote: DesktopObjectDigest | null) => remote?.size === installer.digest.size && remote.sha512 === installer.digest.sha512 const remote = await transport.read(artifact.key, false) diff --git a/apps/desktop/scripts/publish-desktop-rollout-ci.ts b/apps/desktop-publisher/src/publish-desktop-rollout-ci.ts similarity index 98% rename from apps/desktop/scripts/publish-desktop-rollout-ci.ts rename to apps/desktop-publisher/src/publish-desktop-rollout-ci.ts index 4ab553b3c3..9a915049f3 100644 --- a/apps/desktop/scripts/publish-desktop-rollout-ci.ts +++ b/apps/desktop-publisher/src/publish-desktop-rollout-ci.ts @@ -4,7 +4,7 @@ import { appendFile } from 'node:fs/promises' import { dirname, join, resolve } from 'node:path' import { z } from 'zod' import { readDesktopPublishConfig, readDesktopUploadCredentials } from './desktop-publish-config.ts' -import { desktopReleasesRoot } from './retain-desktop-ci.ts' +import { desktopReleasesRoot } from './desktop-releases-root.ts' import { readRetainedDesktopManifest, retainedDesktopPath } from './desktop-release-store.ts' import { resolveRetainedDesktopPublication, retainedDesktopPublishApi } from './resolve-retained-desktop-publish-ci.ts' import { createDesktopPublicationRecord, findDesktopPublication, withDesktopChannelLock } from './desktop-publish-record.ts' @@ -49,7 +49,7 @@ export async function prepareDesktopRolloutCi(env: NodeJS.ProcessEnv) { || source.qualification !== (source.target === 'win-x64' ? 'signed' : 'notarized')) { throw new Error('desktop rollout: repository or release qualification mismatch') } - const config = await readDesktopPublishConfig(env.DSH_PACKAGING_CONFIG_DIR!, source.preset) + const config = await readDesktopPublishConfig(z.string().parse(env.DSH_PACKAGING_CONFIG_DIR), source.preset) const environment = source.preset === 'test' ? { DSH_DESKTOP_AUTO_UPDATE_ENV: 'test', DOWNLOAD_TEST_ORIGIN: config.origin, DOWNLOAD_TEST_RELEASE_ID: source.testReleaseId ?? '', DOWNLOAD_TEST_COS_BUCKET: config.bucket } diff --git a/apps/desktop/scripts/publish-website-ci.ts b/apps/desktop-publisher/src/publish-website-ci.ts similarity index 97% rename from apps/desktop/scripts/publish-website-ci.ts rename to apps/desktop-publisher/src/publish-website-ci.ts index bd3c32f517..00b0ab96c3 100644 --- a/apps/desktop/scripts/publish-website-ci.ts +++ b/apps/desktop-publisher/src/publish-website-ci.ts @@ -5,7 +5,7 @@ import { dirname, join, resolve } from 'node:path' import { setTimeout as sleep } from 'node:timers/promises' import { z } from 'zod' import { readDesktopPublishConfig, readDesktopUploadCredentials } from './desktop-publish-config.ts' -import { desktopReleasesRoot } from './retain-desktop-ci.ts' +import { desktopReleasesRoot } from './desktop-releases-root.ts' import { readRetainedDesktopManifest, retainedDesktopPath } from './desktop-release-store.ts' import { prepareWebsiteInstaller, uploadWebsiteInstaller } from './desktop-website-installer.ts' import { desktopPublishCos } from './desktop-publish-cos.ts' @@ -45,7 +45,7 @@ export async function publishWebsiteCi(mode: 'upload' | 'purge', env: NodeJS.Pro || !/^[1-9]\d*$/u.test(env.GITHUB_RUN_ATTEMPT || '')) throw new Error('website publication: invalid Actions identity or original machine') const root = desktopReleasesRoot(env) const manifest = await readRetainedDesktopManifest(root, route.runId, route.attempt) - const config = await readDesktopPublishConfig(env.DSH_PACKAGING_CONFIG_DIR!, 'production') + const config = await readDesktopPublishConfig(z.string().parse(env.DSH_PACKAGING_CONFIG_DIR), 'production') const approval = websiteApproval(manifest, config.bucket) if (!env.DESKTOP_WEBSITE_APPROVAL || env.DESKTOP_WEBSITE_APPROVAL !== approval) throw new Error('website publication: approved build or destination changed') const zoneId = env.DOWNLOAD_PROD_EO_ZONE_ID @@ -68,7 +68,7 @@ export async function publishWebsiteCi(mode: 'upload' | 'purge', env: NodeJS.Pro const installer = await prepareWebsiteInstaller(retainedDesktopPath(root, route.runId, route.attempt), manifest, route, env.GITHUB_REPOSITORY || '', config.bucket) try { - const outcome = await withDesktopChannelLock(join(dirname(root), 'publish-locks'), `${config.bucket}/${installer.plan.artifacts[0]!.key}`, async () => { + const outcome = await withDesktopChannelLock(join(dirname(root), 'publish-locks'), `${config.bucket}/${installer.plan.artifacts[0].key}`, async () => { const previouslyUploaded = state.uploadConfirmed === true || state.upload === 'uploaded' return uploadWebsiteInstaller(installer, credentials, desktopPublishCos(installer.plan, credentials), async (event) => { state = event === 'upload-intent' diff --git a/apps/desktop/scripts/resolve-desktop-publish-ci.ts b/apps/desktop-publisher/src/resolve-desktop-publish-ci.ts similarity index 95% rename from apps/desktop/scripts/resolve-desktop-publish-ci.ts rename to apps/desktop-publisher/src/resolve-desktop-publish-ci.ts index d1ad2264d4..1f7dfce063 100644 --- a/apps/desktop/scripts/resolve-desktop-publish-ci.ts +++ b/apps/desktop-publisher/src/resolve-desktop-publish-ci.ts @@ -53,12 +53,12 @@ export function selectDesktopPackage(repository: string, inputsValue: unknown, r } packages = packages.filter(job => job.run_attempt === run.run_attempt && job.conclusion === 'success' && job.runner_name) if (packages.length !== 1) throw new Error('desktop publish: expected one successful package job') - const runnerName = packages[0]!.runner_name! + const runnerName = z.string().parse(packages[0]?.runner_name) const routes = desktopPublishRunnersSchema.parse(routesValue) const route = routes[runnerName] const target = (Object.keys(desktopPackageWorkflows) as Array) - .find(name => desktopPackageWorkflows[name] === run.path)! - if (!route || !route.target.includes(target)) throw new Error('desktop publish: original machine has no configured publishing route') + .find(name => desktopPackageWorkflows[name] === run.path) + if (!route || target === undefined || !route.target.includes(target)) throw new Error('desktop publish: original machine has no configured publishing route') if (new Set(Object.values(routes).map(value => value.label)).size !== Object.keys(routes).length) { throw new Error('desktop publish: each configured machine needs its own unique runner label') } diff --git a/apps/desktop/scripts/resolve-retained-desktop-publish-ci.ts b/apps/desktop-publisher/src/resolve-retained-desktop-publish-ci.ts similarity index 95% rename from apps/desktop/scripts/resolve-retained-desktop-publish-ci.ts rename to apps/desktop-publisher/src/resolve-retained-desktop-publish-ci.ts index 1f2526e78a..99c50b26fc 100644 --- a/apps/desktop/scripts/resolve-retained-desktop-publish-ci.ts +++ b/apps/desktop-publisher/src/resolve-retained-desktop-publish-ci.ts @@ -2,7 +2,7 @@ import { appendFile } from 'node:fs/promises' import { resolve } from 'node:path' import { z } from 'zod' -import { desktopReleasesRoot } from './retain-desktop-ci.ts' +import { desktopReleasesRoot } from './desktop-releases-root.ts' import { verifyRetainedDesktopRelease } from './desktop-release-store.ts' import { resolveDesktopPublishRoute } from './desktop-publish-route.ts' @@ -15,7 +15,7 @@ import { resolveDesktopPublishRoute } from './desktop-publish-route.ts' */ export async function resolveRetainedDesktopPublication(env: NodeJS.ProcessEnv, api: (path: string) => unknown, readManifest = verifyRetainedDesktopRelease) { - const selection = z.object({ run: z.object({ id: z.number().int().positive(), run_attempt: z.number().int().positive() }).passthrough(), + const selection = z.object({ run: z.object({ id: z.number().int().positive(), run_attempt: z.number().int().positive() }).loose(), jobs: z.array(z.unknown()), routes: z.unknown(), runnerName: z.string() }).parse(JSON.parse(env.DESKTOP_PACKAGE_SELECTION || '{}')) if (!env.GITHUB_REPOSITORY || env.RUNNER_NAME !== selection.runnerName) throw new Error('desktop publish: task was dispatched to a different machine') const manifest = await readManifest(desktopReleasesRoot(env), String(selection.run.id), String(selection.run.run_attempt)) @@ -52,7 +52,7 @@ export function retainedDesktopPublishApi(env: NodeJS.ProcessEnv): (path: string signal: AbortSignal.timeout(60_000), }) if (!response.ok) throw new Error(`desktop publish: GitHub verification request failed (HTTP ${response.status})`) - return response.json() + return response.json() as Promise } } diff --git a/apps/desktop/tests/cos-loopback.ts b/apps/desktop-publisher/tests/cos-loopback.ts similarity index 100% rename from apps/desktop/tests/cos-loopback.ts rename to apps/desktop-publisher/tests/cos-loopback.ts diff --git a/apps/desktop/tests/cos-operation.spec.ts b/apps/desktop-publisher/tests/cos-operation.spec.ts similarity index 96% rename from apps/desktop/tests/cos-operation.spec.ts rename to apps/desktop-publisher/tests/cos-operation.spec.ts index 0a065363a0..d653d2e751 100644 --- a/apps/desktop/tests/cos-operation.spec.ts +++ b/apps/desktop-publisher/tests/cos-operation.spec.ts @@ -1,8 +1,8 @@ import { Readable, Writable } from 'node:stream' import type { ServerResponse } from 'node:http' import { afterEach, describe, expect, it, vi } from 'vitest' -import { cosOperation } from '../scripts/cos-operation.ts' -import { createDesktopCos } from '../scripts/desktop-cos.ts' +import { cosOperation } from '@deepseek-ai/dsh-desktop-publisher/cos-operation.ts' +import { createDesktopCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import { answer, cosError, startCosLoopback, type CosLoopback } from './cos-loopback.ts' const loopbacks: CosLoopback[] = [] diff --git a/apps/desktop/tests/desktop-auto-update-environment.spec.ts b/apps/desktop-publisher/tests/desktop-auto-update-environment.spec.ts similarity index 98% rename from apps/desktop/tests/desktop-auto-update-environment.spec.ts rename to apps/desktop-publisher/tests/desktop-auto-update-environment.spec.ts index 74fabee903..8b49573531 100644 --- a/apps/desktop/tests/desktop-auto-update-environment.spec.ts +++ b/apps/desktop-publisher/tests/desktop-auto-update-environment.spec.ts @@ -7,7 +7,7 @@ import { resolveDesktopAutoUpdateEnvironment, resolveDesktopAutoUpdateTarget, resolveDesktopUploadConfig, -} from '../scripts/desktop-auto-update-environment.mjs' +} from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' const RELEASE_ID = '0123456789abcdef0123456789abcdef' diff --git a/apps/desktop/tests/desktop-package-selection.spec.ts b/apps/desktop-publisher/tests/desktop-package-selection.spec.ts similarity index 97% rename from apps/desktop/tests/desktop-package-selection.spec.ts rename to apps/desktop-publisher/tests/desktop-package-selection.spec.ts index 54d2aaec13..0d5342b2be 100644 --- a/apps/desktop/tests/desktop-package-selection.spec.ts +++ b/apps/desktop-publisher/tests/desktop-package-selection.spec.ts @@ -2,9 +2,9 @@ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, it } from 'vitest' -import { selectDesktopPackage } from '../scripts/resolve-desktop-publish-ci.ts' -import { resolveRetainedDesktopPublication } from '../scripts/resolve-retained-desktop-publish-ci.ts' -import { retainDesktopRelease, verifyRetainedDesktopRelease } from '../scripts/desktop-release-store.ts' +import { selectDesktopPackage } from '../src/resolve-desktop-publish-ci.ts' +import { resolveRetainedDesktopPublication } from '@deepseek-ai/dsh-desktop-publisher/resolve-retained-desktop-publish-ci.ts' +import { retainDesktopRelease, verifyRetainedDesktopRelease } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' function fixture() { const run = { id: 42, run_attempt: 2, head_sha: 'a'.repeat(40), status: 'completed', conclusion: 'success', diff --git a/apps/desktop/tests/desktop-publication-failure.spec.ts b/apps/desktop-publisher/tests/desktop-publication-failure.spec.ts similarity index 89% rename from apps/desktop/tests/desktop-publication-failure.spec.ts rename to apps/desktop-publisher/tests/desktop-publication-failure.spec.ts index 721b839ba8..f8ced04f73 100644 --- a/apps/desktop/tests/desktop-publication-failure.spec.ts +++ b/apps/desktop-publisher/tests/desktop-publication-failure.spec.ts @@ -2,8 +2,8 @@ import { spawnSync } from 'node:child_process' import { fileURLToPath } from 'node:url' import { expect, it } from 'vitest' import { z } from 'zod' -import { DesktopCosOperationError, desktopPublicationFailure } from '../scripts/desktop-publication-failure.ts' -import { DesktopPublishError } from '../scripts/desktop-publish.ts' +import { DesktopCosOperationError, desktopPublicationFailure } from '@deepseek-ai/dsh-desktop-publisher/desktop-publication-failure.ts' +import { DesktopPublishError } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts' it('preserves actionable validation and filesystem diagnostics', () => { expect(desktopPublicationFailure(new DesktopPublishError('conflict', 'desktop publish: object differs: bin/app.exe'), 'upload')) @@ -26,7 +26,7 @@ it('does not retain provider bodies, unknown messages, JSON input or invalid fie it('prints rollback usage through the real CLI before any audit or remote operation', () => { const result = spawnSync(process.execPath, ['--import', 'tsx/esm', - fileURLToPath(new URL('../scripts/rollback-desktop-channel.ts', import.meta.url))], { encoding: 'utf8', timeout: 30_000 }) + fileURLToPath(new URL('../../desktop/scripts/rollback-desktop-channel.ts', import.meta.url))], { encoding: 'utf8', timeout: 30_000 }) expect(result.error).toBeUndefined() expect(result.signal).toBeNull() expect(result.status).toBe(1) @@ -47,7 +47,7 @@ it('omits malformed provider receipt fields and never copies raw errors into COS it('prints structured archival failure through the real CLI', () => { const result = spawnSync(process.execPath, ['--import', 'tsx/esm', - fileURLToPath(new URL('../scripts/archive-desktop-ci.ts', import.meta.url))], { + fileURLToPath(new URL('../../desktop/scripts/archive-desktop-ci.ts', import.meta.url))], { encoding: 'utf8', timeout: 30_000, env: { ...process.env, DESKTOP_ARCHIVE_NAME: '', GITHUB_OUTPUT: '' }, }) expect(result.error).toBeUndefined() @@ -66,7 +66,7 @@ it.each(['percentage cannot decrease; inspect the current rollout', 'feed change it.each([['check', 'extra'], ['route']])('prints actionable rollout CLI failures for %s', (...args) => { const result = spawnSync(process.execPath, ['--import', 'tsx/esm', - fileURLToPath(new URL('../scripts/publish-desktop-rollout-ci.ts', import.meta.url)), ...args], { + fileURLToPath(new URL('../src/publish-desktop-rollout-ci.ts', import.meta.url)), ...args], { encoding: 'utf8', timeout: 30_000, env: { ...process.env, GITHUB_OUTPUT: '', GH_TOKEN: '' }, }) expect(result.error).toBeUndefined() diff --git a/apps/desktop/tests/desktop-publish-config.spec.ts b/apps/desktop-publisher/tests/desktop-publish-config.spec.ts similarity index 97% rename from apps/desktop/tests/desktop-publish-config.spec.ts rename to apps/desktop-publisher/tests/desktop-publish-config.spec.ts index 9577581d82..eaf0dd722f 100644 --- a/apps/desktop/tests/desktop-publish-config.spec.ts +++ b/apps/desktop-publisher/tests/desktop-publish-config.spec.ts @@ -2,7 +2,7 @@ import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, it } from 'vitest' -import { readDesktopPublishConfig, readDesktopUploadCredentials } from '../scripts/desktop-publish-config.ts' +import { readDesktopPublishConfig, readDesktopUploadCredentials } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-config.ts' it('reads public settings without opening the absent credential file and requires production App settings', async () => { const root = await mkdtemp(join(tmpdir(), 'publish-config-')) diff --git a/apps/desktop/tests/desktop-publish-cos.spec.ts b/apps/desktop-publisher/tests/desktop-publish-cos.spec.ts similarity index 91% rename from apps/desktop/tests/desktop-publish-cos.spec.ts rename to apps/desktop-publisher/tests/desktop-publish-cos.spec.ts index 4b42562d40..3b00ae23e7 100644 --- a/apps/desktop/tests/desktop-publish-cos.spec.ts +++ b/apps/desktop-publisher/tests/desktop-publish-cos.spec.ts @@ -1,10 +1,10 @@ import { expect, it } from 'vitest' -import { createDesktopCos } from '../scripts/desktop-cos.ts' -import { desktopPublishCos } from '../scripts/desktop-publish-cos.ts' -import { desktopArtifactDigest } from '../scripts/desktop-publish.ts' -import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' +import { createDesktopCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' +import { desktopPublishCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-cos.ts' +import { desktopArtifactDigest } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts' +import type { DesktopUploadPlan } from '../src/desktop-upload-types.ts' import { answer, cosError, startCosLoopback } from './cos-loopback.ts' -import { desktopPublicationFailure } from '../scripts/desktop-publication-failure.ts' +import { desktopPublicationFailure } from '@deepseek-ai/dsh-desktop-publisher/desktop-publication-failure.ts' it.each([true, false])('preserves download headers and verified bytes with overwrite prevention %s', async (forbidOverwrite) => { const objects = new Map() diff --git a/apps/desktop/tests/desktop-publish-record.spec.ts b/apps/desktop-publisher/tests/desktop-publish-record.spec.ts similarity index 96% rename from apps/desktop/tests/desktop-publish-record.spec.ts rename to apps/desktop-publisher/tests/desktop-publish-record.spec.ts index 287af3e4a2..530e9ae3bf 100644 --- a/apps/desktop/tests/desktop-publish-record.spec.ts +++ b/apps/desktop-publisher/tests/desktop-publish-record.spec.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { promisify } from 'node:util' import { expect, it } from 'vitest' -import { createDesktopPublicationRecord, wasDesktopAttemptPublished, withDesktopChannelLock } from '../scripts/desktop-publish-record.ts' +import { createDesktopPublicationRecord, wasDesktopAttemptPublished, withDesktopChannelLock } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-record.ts' it('excludes another process while a channel lock is held and admits it after release', async () => { const root = await mkdtemp(join(tmpdir(), 'desktop-process-lock-')) @@ -18,7 +18,7 @@ it('excludes another process while a channel lock is held and admits it after re } ` const contender = () => promisify(execFile)(process.execPath, ['--import', 'tsx/esm', '--input-type=module', '-e', script, - new URL('../scripts/desktop-publish-record.ts', import.meta.url).href, root], { encoding: 'utf8' }) + new URL('../src/desktop-publish-record.ts', import.meta.url).href, root], { encoding: 'utf8' }) try { await withDesktopChannelLock(root, 'bucket/mac', async () => { expect((await contender()).stdout).toBe('locked') diff --git a/apps/desktop/tests/desktop-publish-route.spec.ts b/apps/desktop-publisher/tests/desktop-publish-route.spec.ts similarity index 98% rename from apps/desktop/tests/desktop-publish-route.spec.ts rename to apps/desktop-publisher/tests/desktop-publish-route.spec.ts index a4e1acb8a1..049863932e 100644 --- a/apps/desktop/tests/desktop-publish-route.spec.ts +++ b/apps/desktop-publisher/tests/desktop-publish-route.spec.ts @@ -1,5 +1,5 @@ import { expect, it } from 'vitest' -import { resolveDesktopPublishRoute } from '../scripts/desktop-publish-route.ts' +import { resolveDesktopPublishRoute } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-route.ts' function fixture() { const run = { id: 42, run_attempt: 2, head_sha: 'a'.repeat(40), path: '.github/workflows/macos-package.yml', diff --git a/apps/desktop/tests/desktop-publish.spec.ts b/apps/desktop-publisher/tests/desktop-publish.spec.ts similarity index 97% rename from apps/desktop/tests/desktop-publish.spec.ts rename to apps/desktop-publisher/tests/desktop-publish.spec.ts index cf88751230..408129a913 100644 --- a/apps/desktop/tests/desktop-publish.spec.ts +++ b/apps/desktop-publisher/tests/desktop-publish.spec.ts @@ -1,7 +1,7 @@ import { createHash } from 'node:crypto' import { expect, it } from 'vitest' -import { publishDesktopRelease, type DesktopPublishEvent, type DesktopPublishOperations, type DesktopRemoteObject } from '../scripts/desktop-publish.ts' -import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' +import { publishDesktopRelease, type DesktopPublishEvent, type DesktopPublishOperations, type DesktopRemoteObject } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts' +import type { DesktopUploadPlan } from '../src/desktop-upload-types.ts' function observed(contents: string): DesktopRemoteObject { return { contents, size: Buffer.byteLength(contents), sha512: createHash('sha512').update(contents).digest('base64') } diff --git a/apps/desktop/tests/desktop-purge-recovery.spec.ts b/apps/desktop-publisher/tests/desktop-purge-recovery.spec.ts similarity index 97% rename from apps/desktop/tests/desktop-purge-recovery.spec.ts rename to apps/desktop-publisher/tests/desktop-purge-recovery.spec.ts index 2b4781fcce..19b78bd29e 100644 --- a/apps/desktop/tests/desktop-purge-recovery.spec.ts +++ b/apps/desktop-publisher/tests/desktop-purge-recovery.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' -import { desktopPublicationFailure } from '../scripts/desktop-publication-failure.ts' -import { recoverDesktopPurge, type DesktopPurgeRecord, type DesktopPurgeRecoveryOptions } from '../scripts/desktop-purge-recovery.ts' +import { desktopPublicationFailure } from '@deepseek-ai/dsh-desktop-publisher/desktop-publication-failure.ts' +import { recoverDesktopPurge, type DesktopPurgeRecord, type DesktopPurgeRecoveryOptions } from '@deepseek-ai/dsh-desktop-publisher/desktop-purge-recovery.ts' const config = { zoneId: 'zone-test', publicUrl: 'https://download.deepseek.com/desktop/test.dmg', secretId: 'secret-id', secretKey: 'secret-key' } const submittedAt = '2026-10-30T00:00:00.000Z' diff --git a/apps/desktop/tests/desktop-release-store.spec.ts b/apps/desktop-publisher/tests/desktop-release-store.spec.ts similarity index 97% rename from apps/desktop/tests/desktop-release-store.spec.ts rename to apps/desktop-publisher/tests/desktop-release-store.spec.ts index 899b38b8cf..0f0b427a02 100644 --- a/apps/desktop/tests/desktop-release-store.spec.ts +++ b/apps/desktop-publisher/tests/desktop-release-store.spec.ts @@ -2,7 +2,7 @@ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it } from 'vitest' -import { retainDesktopRelease, retainedDesktopPath, verifyRetainedDesktopRelease, type DesktopRetainedSource } from '../scripts/desktop-release-store.ts' +import { retainDesktopRelease, retainedDesktopPath, verifyRetainedDesktopRelease, type DesktopRetainedSource } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' const roots: string[] = [] afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))) }) diff --git a/apps/desktop/tests/desktop-website-installer.spec.ts b/apps/desktop-publisher/tests/desktop-website-installer.spec.ts similarity index 94% rename from apps/desktop/tests/desktop-website-installer.spec.ts rename to apps/desktop-publisher/tests/desktop-website-installer.spec.ts index d3c2a2a623..56a717f2a3 100644 --- a/apps/desktop/tests/desktop-website-installer.spec.ts +++ b/apps/desktop-publisher/tests/desktop-website-installer.spec.ts @@ -3,12 +3,12 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it } from 'vitest' -import { createDesktopCos } from '../scripts/desktop-cos.ts' -import { desktopPublishCos } from '../scripts/desktop-publish-cos.ts' +import { createDesktopCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' +import { desktopPublishCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-cos.ts' import { answer, cosError, startCosLoopback } from './cos-loopback.ts' -import { prepareWebsiteInstaller, uploadWebsiteInstaller } from '../scripts/desktop-website-installer.ts' -import type { DesktopRetainedManifest } from '../scripts/desktop-release-store.ts' -import type { DesktopPublishRoute } from '../scripts/desktop-publish-route.ts' +import { prepareWebsiteInstaller, uploadWebsiteInstaller } from '@deepseek-ai/dsh-desktop-publisher/desktop-website-installer.ts' +import type { DesktopRetainedManifest } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' +import type { DesktopPublishRoute } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-route.ts' const roots: string[] = [] afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))) }) diff --git a/apps/desktop/tests/expected/cos-GetObject-denied.json b/apps/desktop-publisher/tests/expected/cos-GetObject-denied.json similarity index 100% rename from apps/desktop/tests/expected/cos-GetObject-denied.json rename to apps/desktop-publisher/tests/expected/cos-GetObject-denied.json diff --git a/apps/desktop/tests/expected/cos-PutObject-denied.json b/apps/desktop-publisher/tests/expected/cos-PutObject-denied.json similarity index 100% rename from apps/desktop/tests/expected/cos-PutObject-denied.json rename to apps/desktop-publisher/tests/expected/cos-PutObject-denied.json diff --git a/apps/desktop/tests/expected/website-purge-accepted.md b/apps/desktop-publisher/tests/expected/website-purge-accepted.md similarity index 100% rename from apps/desktop/tests/expected/website-purge-accepted.md rename to apps/desktop-publisher/tests/expected/website-purge-accepted.md diff --git a/apps/desktop/tests/expected/website-purge-unconfirmed.md b/apps/desktop-publisher/tests/expected/website-purge-unconfirmed.md similarity index 100% rename from apps/desktop/tests/expected/website-purge-unconfirmed.md rename to apps/desktop-publisher/tests/expected/website-purge-unconfirmed.md diff --git a/apps/desktop-publisher/tests/isolated-install.mjs b/apps/desktop-publisher/tests/isolated-install.mjs new file mode 100644 index 0000000000..049c56522f --- /dev/null +++ b/apps/desktop-publisher/tests/isolated-install.mjs @@ -0,0 +1,18 @@ +/** Run only in a clean checkout after installing this workspace's production dependencies. */ +import '../src/resolve-desktop-publish-ci.ts' +import assert from 'node:assert/strict' +import { existsSync } from 'node:fs' +import { createRequire } from 'node:module' +import { prepareDesktopRolloutCi } from '../src/publish-desktop-rollout-ci.ts' +import { desktopReleasesRoot } from '../src/desktop-releases-root.ts' +import { teo } from 'tencentcloud-sdk-nodejs-teo' + +const require = createRequire(import.meta.url) +for (const dependency of ['electron', 'electron-builder', 'app-builder-lib', 'react', 'vite', 'typescript']) { + assert.throws(() => require.resolve(dependency), { code: 'MODULE_NOT_FOUND' }, `${dependency} must not be installed`) +} +assert.equal(existsSync(new URL('../../desktop/node_modules', import.meta.url)), false) +assert.equal(typeof teo.v20220901.Client, 'function') +assert.throws(() => desktopReleasesRoot({}), /DSH_PACKAGING_CONFIG_DIR is required/) +await assert.rejects(prepareDesktopRolloutCi({}), /runId/) +console.log('Desktop publisher isolated install: OK (no package build, credentials or remote operations)') diff --git a/apps/desktop/tests/publish-website-ci.spec.ts b/apps/desktop-publisher/tests/publish-website-ci.spec.ts similarity index 97% rename from apps/desktop/tests/publish-website-ci.spec.ts rename to apps/desktop-publisher/tests/publish-website-ci.spec.ts index 2c75150bc4..cdac810fb6 100644 --- a/apps/desktop/tests/publish-website-ci.spec.ts +++ b/apps/desktop-publisher/tests/publish-website-ci.spec.ts @@ -3,10 +3,10 @@ import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' -import * as desktopCos from '../scripts/desktop-cos.ts' +import * as desktopCos from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import { answer, cosError, startCosLoopback } from './cos-loopback.ts' import { teo } from 'tencentcloud-sdk-nodejs-teo' -import { publishWebsiteCi, websiteApproval } from '../scripts/publish-website-ci.ts' +import { publishWebsiteCi, websiteApproval } from '@deepseek-ai/dsh-desktop-publisher/publish-website-ci.ts' vi.mock('node:timers/promises', () => ({ setTimeout: async () => {} })) afterEach(() => vi.restoreAllMocks()) diff --git a/apps/desktop-publisher/tests/workflow.spec.ts b/apps/desktop-publisher/tests/workflow.spec.ts new file mode 100644 index 0000000000..738412c54a --- /dev/null +++ b/apps/desktop-publisher/tests/workflow.spec.ts @@ -0,0 +1,31 @@ +import { existsSync, readFileSync } from 'node:fs' +import { resolve, relative } from 'node:path' +import { load } from 'js-yaml' +import { z } from 'zod' +import { expect, it } from 'vitest' + +const root = resolve(import.meta.dirname, '../../..') +const step = z.object({ + uses: z.string().optional(), run: z.string().optional(), + 'working-directory': z.string().optional(), + with: z.object({ path: z.string().optional() }).loose().optional(), +}).loose() +const workflowSchema = z.object({ jobs: z.record(z.string(), z.object({ steps: z.array(step) }).loose()) }) + +it('loads every rollout entry from its own installed package and the correct job checkout', () => { + const workflow = workflowSchema.parse(load(readFileSync(resolve(root, '.github/workflows/desktop-rollout.yml'), 'utf8'))) + for (const job of Object.values(workflow.jobs)) { + const checkout = job.steps.find(entry => entry.uses?.startsWith('actions/checkout@')) + const checkoutRoot = resolve(root, checkout?.with?.path ?? '.') + const install = job.steps.find(entry => entry.run?.includes(' install ')) + expect(install?.run).toContain('--filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts') + for (const entry of job.steps) { + if (!entry.run?.startsWith('node --import tsx ')) continue + const directory = relative(checkoutRoot, resolve(root, entry['working-directory'] ?? '.')) + expect(directory).toBe('apps/desktop-publisher') + const script = entry.run.split(' ')[3]! + expect(existsSync(resolve(root, directory, script))).toBe(true) + } + expect(job.steps.some(entry => entry.run?.includes('pnpm exec'))).toBe(false) + } +}) diff --git a/apps/desktop/package.json b/apps/desktop/package.json index c3cf87bfa4..1642eeecd9 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -90,6 +90,7 @@ "zod": "4.6.6", "@deepseek-ai/dsh-util-file-drag": "workspace:*", "@deepseek-ai/dsh-client-ui-file-actions": "workspace:*", - "tencentcloud-sdk-nodejs-teo": "4.1.330" + "tencentcloud-sdk-nodejs-teo": "4.1.330", + "@deepseek-ai/dsh-desktop-publisher": "workspace:*" } } diff --git a/apps/desktop/scripts/archive-desktop-ci.ts b/apps/desktop/scripts/archive-desktop-ci.ts index 1517d20dd4..3d36b4fcc6 100644 --- a/apps/desktop/scripts/archive-desktop-ci.ts +++ b/apps/desktop/scripts/archive-desktop-ci.ts @@ -2,9 +2,9 @@ import { execFileSync } from 'node:child_process' import { appendFile, mkdtemp } from 'node:fs/promises' import { join, resolve } from 'node:path' -import { desktopPublicationFailure } from './desktop-publication-failure.ts' +import { desktopPublicationFailure } from '@deepseek-ai/dsh-desktop-publisher/desktop-publication-failure.ts' import { desktopReleasesRoot } from './retain-desktop-ci.ts' -import { retainedDesktopPath, verifyRetainedDesktopRelease } from './desktop-release-store.ts' +import { retainedDesktopPath, verifyRetainedDesktopRelease } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' /** * Verify an original build without interpreting the archive job's attempt as a new build. diff --git a/apps/desktop/scripts/desktop-build-paths.d.mts b/apps/desktop/scripts/desktop-build-paths.d.mts index 910f3032ee..aaf7159d44 100644 --- a/apps/desktop/scripts/desktop-build-paths.d.mts +++ b/apps/desktop/scripts/desktop-build-paths.d.mts @@ -1,4 +1,4 @@ -import type { DesktopAutoUpdateTarget } from './desktop-auto-update-environment.mjs' +import type { DesktopAutoUpdateTarget } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' /** Mutable target directories plus shared download and package caches. */ export interface DesktopTargetBuildPaths { diff --git a/apps/desktop/scripts/desktop-build-version-discovery.ts b/apps/desktop/scripts/desktop-build-version-discovery.ts index 68291ca3b8..d9e87b6965 100644 --- a/apps/desktop/scripts/desktop-build-version-discovery.ts +++ b/apps/desktop/scripts/desktop-build-version-discovery.ts @@ -20,8 +20,8 @@ import { readdir } from 'node:fs/promises' import { parse } from 'semver' import { desktopBuildVersionPrefix, validateDesktopBuildVersion } from './desktop-build-version.mjs' -import { DESKTOP_AUTO_UPDATE_ENV, resolveDesktopUploadConfig } from './desktop-auto-update-environment.mjs' -import { createDesktopCos, DESKTOP_COS_REGION } from './desktop-cos.ts' +import { DESKTOP_AUTO_UPDATE_ENV, resolveDesktopUploadConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' +import { createDesktopCos, DESKTOP_COS_REGION } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import type { DesktopPackageTargetName } from './package-target.ts' /** How long the whole bucket listing may take before the suggestion falls back to local artifacts. */ diff --git a/apps/desktop/scripts/desktop-edgeone.ts b/apps/desktop/scripts/desktop-edgeone.ts index e2faf122a0..dedbd8ad1d 100644 --- a/apps/desktop/scripts/desktop-edgeone.ts +++ b/apps/desktop/scripts/desktop-edgeone.ts @@ -1,16 +1,11 @@ /** Submit one production fixed-installer cache purge to EdgeOne. */ import type { teo } from 'tencentcloud-sdk-nodejs-teo' import type { DesktopPackageTargetName } from './package-target.ts' -import { desktopLatestInstallerFilename, requiredEnvironmentValue, resolveDesktopAutoUpdateEnvironment, resolveDesktopUploadConfig } from './desktop-auto-update-environment.mjs' +import { desktopLatestInstallerFilename, requiredEnvironmentValue, resolveDesktopAutoUpdateEnvironment, resolveDesktopUploadConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { desktopTargetPlatform } from './desktop-build-paths.mjs' -/** Validated production destination and credentials; never serialize this value. */ -export interface DesktopPurgeConfig { - readonly zoneId: string - readonly publicUrl: string - readonly secretId: string - readonly secretKey: string -} +import type { DesktopPurgeConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-purge-types.ts' +export type { DesktopPurgeConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-purge-types.ts' /** The single SDK operation needed to submit a purge. */ export type DesktopPurgeClient = Pick, 'CreatePurgeTask'> diff --git a/apps/desktop/scripts/desktop-package-environment.mjs b/apps/desktop/scripts/desktop-package-environment.mjs index 83e9dbbc0f..d301ac4b31 100644 --- a/apps/desktop/scripts/desktop-package-environment.mjs +++ b/apps/desktop/scripts/desktop-package-environment.mjs @@ -5,7 +5,7 @@ import { dirname, isAbsolute, join } from 'node:path' import { fileURLToPath } from 'node:url' import { readDesktopPackageSettings as readSettings } from './desktop-file-settings.mjs' import { resolveDesktopAppId, resolveMacOSNotarizationEnvironment, resolveMacOSSigningEnvironment, resolveNpmRegistry } from './desktop-release-environment.mjs' -import { resolveDesktopAutoUpdateConfig } from './desktop-auto-update-environment.mjs' +import { resolveDesktopAutoUpdateConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { createWindowsTokenSigner } from './windows-sign.mjs' import { resolveDesktopPolicyEnvironment } from './desktop-policy-environment.mjs' import { validateMacOSSignatureCacheDirectory } from './macos-signature-cache-directory.mjs' diff --git a/apps/desktop/scripts/desktop-policy-environment.mjs b/apps/desktop/scripts/desktop-policy-environment.mjs index 591147578b..dafaa417ea 100644 --- a/apps/desktop/scripts/desktop-policy-environment.mjs +++ b/apps/desktop/scripts/desktop-policy-environment.mjs @@ -1,5 +1,5 @@ /** Resolve the required policy service from the same deployment as updater publication. */ -import { resolveDesktopAutoUpdateEnvironment } from './desktop-auto-update-environment.mjs' +import { resolveDesktopAutoUpdateEnvironment } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' function origin(value, name) { let url diff --git a/apps/desktop/scripts/desktop-publication-summary.ts b/apps/desktop/scripts/desktop-publication-summary.ts index a9e86575fd..13dfd0ae51 100644 --- a/apps/desktop/scripts/desktop-publication-summary.ts +++ b/apps/desktop/scripts/desktop-publication-summary.ts @@ -3,8 +3,8 @@ import { load } from 'js-yaml' import { z } from 'zod' import { createHash } from 'node:crypto' import { createReadStream } from 'node:fs' -import { desktopWebsiteInstallerUrl } from './desktop-auto-update-environment.mjs' -import type { DesktopRetainedSource } from './desktop-release-store.ts' +import { desktopWebsiteInstallerUrl } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' +import type { DesktopRetainedSource } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' import type { DesktopUploadPlan } from './desktop-upload-plan.ts' function text(value: string): string { diff --git a/apps/desktop/scripts/desktop-rollback.ts b/apps/desktop/scripts/desktop-rollback.ts index a96e5d652b..10eacbe555 100644 --- a/apps/desktop/scripts/desktop-rollback.ts +++ b/apps/desktop/scripts/desktop-rollback.ts @@ -2,7 +2,7 @@ import { load } from 'js-yaml' import { z } from 'zod' import type { DesktopUploadPlan } from './desktop-upload-plan.ts' -import { desktopArtifactDigest, type DesktopPublishOperations, type DesktopRemoteObject } from './desktop-publish.ts' +import { desktopArtifactDigest, type DesktopPublishOperations, type DesktopRemoteObject } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts' /** Outcome of an explicitly requested channel restoration. */ export interface DesktopRollbackResult { diff --git a/apps/desktop/scripts/desktop-upload-plan.ts b/apps/desktop/scripts/desktop-upload-plan.ts index 39ff954bf5..9c8d9c47e7 100644 --- a/apps/desktop/scripts/desktop-upload-plan.ts +++ b/apps/desktop/scripts/desktop-upload-plan.ts @@ -11,7 +11,7 @@ import { desktopLatestInstallerFilename, desktopUpdateMetadataFilename, resolveDesktopUploadConfig, -} from './desktop-auto-update-environment.mjs' +} from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { desktopTargetBuildPaths } from './desktop-build-paths.mjs' import { validateDesktopBuildVersion } from './desktop-build-version.mjs' @@ -27,35 +27,8 @@ const TARGETS = { readonly os: string }> -/** One local file and its final object metadata. */ -export interface DesktopUploadArtifact { - readonly path: string - readonly filename: string - readonly key: string - readonly contentType: string - /** Browser save name for fixed website downloads, preserving the validated installer basename. */ - readonly contentDisposition?: string - readonly channelMetadata: boolean - /** Published YAML with normalized artifact URLs; binary bytes remain file-backed. */ - readonly contents?: string -} - -/** A validated installer or update upload, with any channel metadata ordered last. */ -export interface DesktopUploadPlan { - readonly environment: 'test' | 'production' - readonly target: DesktopPackageTargetName - readonly version: string - /** Update feed directory URL, or the single installer URL for a fixed download. */ - readonly publicUrl: string - readonly bucket: string - readonly secretIdEnvName: string - readonly secretKeyEnvName: string - readonly artifacts: readonly DesktopUploadArtifact[] - /** Commit the artifacts were packaged from, absent for a package built before builds recorded it. */ - readonly commit?: string - /** Whether that checkout carried uncommitted changes. */ - readonly dirty?: boolean -} +import type { DesktopUploadArtifact, DesktopUploadPlan } from '@deepseek-ai/dsh-desktop-publisher/desktop-upload-types.ts' +export type { DesktopUploadArtifact, DesktopUploadPlan } from '@deepseek-ai/dsh-desktop-publisher/desktop-upload-types.ts' /** Filesystem and environment inputs used to validate one upload. */ export interface DesktopUploadPlanOptions { diff --git a/apps/desktop/scripts/desktop-upload-run.ts b/apps/desktop/scripts/desktop-upload-run.ts index 3bb305afde..ccf528b1f6 100644 --- a/apps/desktop/scripts/desktop-upload-run.ts +++ b/apps/desktop/scripts/desktop-upload-run.ts @@ -6,7 +6,7 @@ import { join } from 'node:path' import { Readable } from 'node:stream' import type COS from 'cos-nodejs-sdk-v5' import type { DesktopUploadArtifact, DesktopUploadPlan } from './desktop-upload-plan.ts' -import { DESKTOP_COS_REGION } from './desktop-cos.ts' +import { DESKTOP_COS_REGION } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import { recordPackagingEvent } from './packaging-run.mjs' const FAILURE_CODES = new Set(['AccessDenied', 'InternalError', 'NoSuchBucket', 'BadDigest', 'SignatureDoesNotMatch', @@ -84,7 +84,9 @@ export async function uploadDesktopRelease(plan: DesktopUploadPlan, cos: COS, re } const sourceSha256: Record = {} for (const filename of UPLOADER_SOURCES) { - sourceSha256[filename] = createHash('sha256').update(await readFile(join(import.meta.dirname, filename))).digest('hex') + sourceSha256[filename] = createHash('sha256').update(await readFile(filename === 'desktop-cos.ts' + ? new URL(import.meta.resolve('@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts')) + : join(import.meta.dirname, filename))).digest('hex') } await writeFile(join(directory, 'plan.json'), `${JSON.stringify({ schemaVersion: 1, environment: plan.environment, target: plan.target, version: plan.version, bucket: plan.bucket, diff --git a/apps/desktop/scripts/development-project.ts b/apps/desktop/scripts/development-project.ts index d544ce6d36..becb8e79a4 100644 --- a/apps/desktop/scripts/development-project.ts +++ b/apps/desktop/scripts/development-project.ts @@ -16,7 +16,7 @@ import { dirname, join } from 'node:path' import { createDevelopmentProjectMetadata } from '../src/project-manager.ts' import type { DesktopRelease } from '../src/release.ts' import { DESKTOP_RUNTIME_FILE, type DesktopRuntimeDescriptor } from '../src/runtime-tree.ts' -import type { DesktopAutoUpdateTarget } from './desktop-auto-update-environment.mjs' +import type { DesktopAutoUpdateTarget } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { desktopTargetPlatform } from './desktop-build-paths.mjs' interface PackageManifest { diff --git a/apps/desktop/scripts/electron-builder-config.mjs b/apps/desktop/scripts/electron-builder-config.mjs index d5522e3da9..36b0d4e3ba 100644 --- a/apps/desktop/scripts/electron-builder-config.mjs +++ b/apps/desktop/scripts/electron-builder-config.mjs @@ -20,7 +20,7 @@ import { resolveWindowsUpdatePublisher, scrubWindowsSigningEnvironment, } from './windows-sign.mjs' -import { resolveDesktopAutoUpdateConfig } from './desktop-auto-update-environment.mjs' +import { resolveDesktopAutoUpdateConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { resolveDesktopBuildCommit } from './desktop-build-commit.mjs' import { resolveDesktopBuildVersion } from './desktop-build-version.mjs' import { resolveDesktopPolicyEnvironment } from './desktop-policy-environment.mjs' diff --git a/apps/desktop/scripts/installed-update-cos.ts b/apps/desktop/scripts/installed-update-cos.ts index 7dcff940b4..dbc4220aa4 100644 --- a/apps/desktop/scripts/installed-update-cos.ts +++ b/apps/desktop/scripts/installed-update-cos.ts @@ -2,8 +2,8 @@ import { createReadStream } from 'node:fs' import { createHash } from 'node:crypto' import { Readable, Writable } from 'node:stream' -import { cosOperation } from './cos-operation.ts' -import { createDesktopCos, DESKTOP_COS_REGION } from './desktop-cos.ts' +import { cosOperation } from '@deepseek-ai/dsh-desktop-publisher/cos-operation.ts' +import { createDesktopCos, DESKTOP_COS_REGION } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import { loadDesktopPackageEnvironment } from './desktop-package-environment.mjs' import type { InstalledUpdatePublicationStore, InstalledUpdateRemoteObject } from './installed-update-publication.ts' diff --git a/apps/desktop/scripts/macos-app-update-config.mjs b/apps/desktop/scripts/macos-app-update-config.mjs index bdb400bcde..40addd5bf3 100644 --- a/apps/desktop/scripts/macos-app-update-config.mjs +++ b/apps/desktop/scripts/macos-app-update-config.mjs @@ -5,7 +5,7 @@ import { join } from 'node:path' import { dump, load } from 'js-yaml' const CONFIG_FILENAME = 'app-update.yml' -import { resolveDesktopUpdateChannel } from './desktop-auto-update-environment.mjs' +import { resolveDesktopUpdateChannel } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' function object(value, label) { if (typeof value !== 'object' || value === null || Array.isArray(value)) { diff --git a/apps/desktop/scripts/package-macos.ts b/apps/desktop/scripts/package-macos.ts index 4ba0fd12ca..23087c72e6 100644 --- a/apps/desktop/scripts/package-macos.ts +++ b/apps/desktop/scripts/package-macos.ts @@ -13,7 +13,7 @@ import { import { desktopUpdateMetadataFilename, resolveDesktopAutoUpdateConfig, -} from './desktop-auto-update-environment.mjs' +} from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { verifyMacOSAppUpdateConfig } from './macos-app-update-config.mjs' import { verifyMacOSNotarizedApplication, verifyMacOSSignature } from './verify-macos-signature.mjs' diff --git a/apps/desktop/scripts/package-target.ts b/apps/desktop/scripts/package-target.ts index b6bc6efb63..ea244526d5 100644 --- a/apps/desktop/scripts/package-target.ts +++ b/apps/desktop/scripts/package-target.ts @@ -7,7 +7,7 @@ import { join, resolve } from 'node:path' import { desktopBuildRecordFilename, resolveDesktopAutoUpdateConfig, -} from './desktop-auto-update-environment.mjs' +} from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { desktopArtifactOutput, desktopTargetBuildPaths } from './desktop-build-paths.mjs' import { packageMacOSArtifacts, type DesktopPrepackagedArtifact } from './package-macos.ts' import { loadDesktopPackageEnvironment, localMacOSPackageEnvironment, validateDesktopPackageEnvironment } from './desktop-package-environment.mjs' diff --git a/apps/desktop/scripts/preflight-desktop-publish.mjs b/apps/desktop/scripts/preflight-desktop-publish.mjs index fbe6947398..536f3eefa7 100644 --- a/apps/desktop/scripts/preflight-desktop-publish.mjs +++ b/apps/desktop/scripts/preflight-desktop-publish.mjs @@ -2,7 +2,7 @@ import { execFileSync } from 'node:child_process' import { appendFile, readFile } from 'node:fs/promises' import { resolve } from 'node:path' -import { desktopPublishQualificationError } from './desktop-publish-qualification.mjs' +import { desktopPublishQualificationError } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-qualification.mjs' /** * Pin the requested attempt and reject its explicitly named debugging artifacts. diff --git a/apps/desktop/scripts/publish-desktop-ci.ts b/apps/desktop/scripts/publish-desktop-ci.ts index e3d14abbff..cd60886f2e 100644 --- a/apps/desktop/scripts/publish-desktop-ci.ts +++ b/apps/desktop/scripts/publish-desktop-ci.ts @@ -3,19 +3,19 @@ import { createHash } from 'node:crypto' import { appendFile } from 'node:fs/promises' import { dirname, join, resolve } from 'node:path' import { z } from 'zod' -import { readDesktopPublishConfig, readDesktopUploadCredentials } from './desktop-publish-config.ts' +import { readDesktopPublishConfig, readDesktopUploadCredentials } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-config.ts' import { desktopReleasesRoot } from './retain-desktop-ci.ts' -import { retainedDesktopPath, verifyRetainedDesktopRelease } from './desktop-release-store.ts' +import { retainedDesktopPath, verifyRetainedDesktopRelease } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' import { verifyRetainedDesktopSignatures } from './verify-retained-desktop.ts' import { createDesktopUploadPlan } from './desktop-upload-plan.ts' -import { desktopPublishCos } from './desktop-publish-cos.ts' -import { createDesktopPublicationRecord, wasDesktopAttemptPublished, withDesktopChannelLock } from './desktop-publish-record.ts' -import { publishDesktopRelease } from './desktop-publish.ts' -import { desktopPublicationFailure } from './desktop-publication-failure.ts' +import { desktopPublishCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-cos.ts' +import { createDesktopPublicationRecord, wasDesktopAttemptPublished, withDesktopChannelLock } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-record.ts' +import { publishDesktopRelease } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts' +import { desktopPublicationFailure } from '@deepseek-ai/dsh-desktop-publisher/desktop-publication-failure.ts' import { desktopPublicationSummary } from './desktop-publication-summary.ts' import { publishDesktopTag } from './desktop-publish-tag.ts' -import { websiteApproval } from './publish-website-ci.ts' -import { desktopPublishQualificationError } from './desktop-publish-qualification.mjs' +import { websiteApproval } from '@deepseek-ai/dsh-desktop-publisher/publish-website-ci.ts' +import { desktopPublishQualificationError } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-qualification.mjs' const routeSchema = z.object({ runId: z.string(), attempt: z.string(), commit: z.string(), runnerName: z.string(), sourceRef: z.string(), channel: z.enum(['nightly', 'stable']), diff --git a/apps/desktop/scripts/retain-desktop-ci.ts b/apps/desktop/scripts/retain-desktop-ci.ts index e672274992..fb53e9c065 100644 --- a/apps/desktop/scripts/retain-desktop-ci.ts +++ b/apps/desktop/scripts/retain-desktop-ci.ts @@ -1,13 +1,15 @@ +import { desktopReleasesRoot } from '@deepseek-ai/dsh-desktop-publisher/desktop-releases-root.ts' +export { desktopReleasesRoot } from '@deepseek-ai/dsh-desktop-publisher/desktop-releases-root.ts' /** Retain completed CI packages for later manual publication. */ import { appendFile, readFile } from 'node:fs/promises' -import { dirname, isAbsolute, join, resolve } from 'node:path' +import { join, resolve } from 'node:path' import { desktopTargetBuildPaths, resolveDesktopBuildTarget } from './desktop-build-paths.mjs' -import { desktopBuildRecordFilename, desktopUpdateMetadataFilename, resolveDesktopUpdateChannel } from './desktop-auto-update-environment.mjs' +import { desktopBuildRecordFilename, desktopUpdateMetadataFilename, resolveDesktopUpdateChannel } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { loadDesktopPackageEnvironment } from './desktop-package-environment.mjs' -import { retainDesktopRelease, type DesktopRetainedSource } from './desktop-release-store.ts' +import { retainDesktopRelease, type DesktopRetainedSource } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' import { validateDesktopBuildVersion } from './desktop-build-version.mjs' -import { desktopPublishRunnersSchema } from './desktop-publish-targets.ts' -import { desktopPublishQualificationError } from './desktop-publish-qualification.mjs' +import { desktopPublishRunnersSchema } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-targets.ts' +import { desktopPublishQualificationError } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-qualification.mjs' function required(env: NodeJS.ProcessEnv, name: string): string { const value = env[name] @@ -15,17 +17,6 @@ function required(env: NodeJS.ProcessEnv, name: string): string { return value } -/** - * Resolve the persistent release root without assuming a particular user's home directory. - * @param env Machine packaging configuration; an explicit releases directory overrides its sibling default. - * @returns Absolute directory outside the disposable checkout. - */ -export function desktopReleasesRoot(env: NodeJS.ProcessEnv): string { - const configured = required(env, 'DSH_PACKAGING_CONFIG_DIR') - const root = env.DSH_DESKTOP_RELEASES_DIR || join(dirname(configured), 'releases') - if (!isAbsolute(configured) || !isAbsolute(root)) throw new Error('desktop retention: machine directories must be absolute') - return root -} /** * Resolve the original machine's unique label before expensive packaging work. diff --git a/apps/desktop/scripts/rollback-desktop-channel.ts b/apps/desktop/scripts/rollback-desktop-channel.ts index fbefbe4f8b..d799d075a3 100644 --- a/apps/desktop/scripts/rollback-desktop-channel.ts +++ b/apps/desktop/scripts/rollback-desktop-channel.ts @@ -4,11 +4,11 @@ import { dirname, join, resolve } from 'node:path' import { parseArgs } from 'node:util' import { z } from 'zod' import { prepareDesktopPublication } from './publish-desktop-ci.ts' -import { readDesktopUploadCredentials } from './desktop-publish-config.ts' -import { desktopPublishCos } from './desktop-publish-cos.ts' -import { createDesktopPublicationRecord, withDesktopChannelLock } from './desktop-publish-record.ts' +import { readDesktopUploadCredentials } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-config.ts' +import { desktopPublishCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-cos.ts' +import { createDesktopPublicationRecord, withDesktopChannelLock } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-record.ts' import { rollbackDesktopChannel } from './desktop-rollback.ts' -import { desktopPublicationFailure } from './desktop-publication-failure.ts' +import { desktopPublicationFailure } from '@deepseek-ai/dsh-desktop-publisher/desktop-publication-failure.ts' if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.filename) { let phase = 'rollback arguments and local publication verification' diff --git a/apps/desktop/scripts/upload-target.ts b/apps/desktop/scripts/upload-target.ts index a1afdb3241..831d8096f0 100644 --- a/apps/desktop/scripts/upload-target.ts +++ b/apps/desktop/scripts/upload-target.ts @@ -3,8 +3,8 @@ import { resolve } from 'node:path' import { parseArgs } from 'node:util' import type { DesktopPackageTargetName } from './package-target.ts' -import { createDesktopCos } from './desktop-cos.ts' -import { requiredEnvironmentValue, resolveDesktopAutoUpdateEnvironment, resolveDesktopUploadConfig } from './desktop-auto-update-environment.mjs' +import { createDesktopCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' +import { requiredEnvironmentValue, resolveDesktopAutoUpdateEnvironment, resolveDesktopUploadConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { desktopTargetPlatform } from './desktop-build-paths.mjs' import { loadDesktopPackageEnvironment } from './desktop-package-environment.mjs' import { createDesktopUploadPlan, type DesktopUploadPlan } from './desktop-upload-plan.ts' diff --git a/apps/desktop/scripts/verify-retained-desktop.ts b/apps/desktop/scripts/verify-retained-desktop.ts index 613580da9a..fca85421ad 100644 --- a/apps/desktop/scripts/verify-retained-desktop.ts +++ b/apps/desktop/scripts/verify-retained-desktop.ts @@ -3,8 +3,8 @@ import { execFileSync } from 'node:child_process' import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import type { DesktopRetainedManifest } from './desktop-release-store.ts' -import type { DesktopPublishConfig } from './desktop-publish-config.ts' +import type { DesktopRetainedManifest } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' +import type { DesktopPublishConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-config.ts' import { verifyMacOSDiskImage, verifyMacOSNotarizedApplication } from './verify-macos-signature.mjs' /** diff --git a/apps/desktop/tests/desktop-publication-summary.spec.ts b/apps/desktop/tests/desktop-publication-summary.spec.ts index 11ca2d064e..c23273f7b5 100644 --- a/apps/desktop/tests/desktop-publication-summary.spec.ts +++ b/apps/desktop/tests/desktop-publication-summary.spec.ts @@ -1,7 +1,7 @@ import { createHash } from 'node:crypto' import { expect, it } from 'vitest' import { desktopPublicationSummary } from '../scripts/desktop-publication-summary.ts' -import type { DesktopRetainedSource } from '../scripts/desktop-release-store.ts' +import type { DesktopRetainedSource } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' const source: DesktopRetainedSource = { diff --git a/apps/desktop/tests/desktop-publish-templates.spec.ts b/apps/desktop/tests/desktop-publish-templates.spec.ts index 0ead9a11ab..34c2a67d20 100644 --- a/apps/desktop/tests/desktop-publish-templates.spec.ts +++ b/apps/desktop/tests/desktop-publish-templates.spec.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { join, posix, win32 } from 'node:path' import { fileURLToPath } from 'node:url' import { expect, it } from 'vitest' -import { readDesktopPublishConfig, type DesktopPublishConfig } from '../scripts/desktop-publish-config.ts' +import { readDesktopPublishConfig, type DesktopPublishConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-config.ts' for (const platform of ['macos', 'windows'] as const) { for (const preset of ['test', 'production'] as const) { diff --git a/apps/desktop/tests/desktop-rollback.spec.ts b/apps/desktop/tests/desktop-rollback.spec.ts index f7912ea09b..4c858bf613 100644 --- a/apps/desktop/tests/desktop-rollback.spec.ts +++ b/apps/desktop/tests/desktop-rollback.spec.ts @@ -1,7 +1,7 @@ import { createHash } from 'node:crypto' import { expect, it } from 'vitest' import { rollbackDesktopChannel } from '../scripts/desktop-rollback.ts' -import type { DesktopPublishOperations } from '../scripts/desktop-publish.ts' +import type { DesktopPublishOperations } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts' import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' function fixture() { diff --git a/apps/desktop/tests/desktop-rollout.spec.ts b/apps/desktop/tests/desktop-rollout.spec.ts index 8109327090..4637982916 100644 --- a/apps/desktop/tests/desktop-rollout.spec.ts +++ b/apps/desktop/tests/desktop-rollout.spec.ts @@ -7,17 +7,17 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { teo } from 'tencentcloud-sdk-nodejs-teo' import { createDesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' -import { desktopBuildRecordFilename, desktopWebsiteInstallerUrl } from '../scripts/desktop-auto-update-environment.mjs' +import { desktopBuildRecordFilename, desktopWebsiteInstallerUrl } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { dump, load } from 'js-yaml' import { expect, it, vi } from 'vitest' -import { prepareDesktopRollout, rolloutDesktopRelease } from '../scripts/desktop-rollout.ts' -import * as cosTransport from '../scripts/desktop-publish-cos.ts' -import * as websitePublisher from '../scripts/publish-website-ci.ts' -import { prepareDesktopRolloutCi, publishDesktopRolloutCi } from '../scripts/publish-desktop-rollout-ci.ts' -import { createDesktopPublicationRecord } from '../scripts/desktop-publish-record.ts' -import { readRetainedDesktopManifest, type DesktopRetainedManifest } from '../scripts/desktop-release-store.ts' -import { resolveRetainedDesktopPublication } from '../scripts/resolve-retained-desktop-publish-ci.ts' -import type { DesktopPublishEvent, DesktopRemoteObject, DesktopPublishTransport } from '../scripts/desktop-publish.ts' +import { prepareDesktopRollout, rolloutDesktopRelease } from '@deepseek-ai/dsh-desktop-publisher/desktop-rollout.ts' +import * as cosTransport from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-cos.ts' +import * as websitePublisher from '@deepseek-ai/dsh-desktop-publisher/publish-website-ci.ts' +import { prepareDesktopRolloutCi, publishDesktopRolloutCi } from '@deepseek-ai/dsh-desktop-publisher/publish-desktop-rollout-ci.ts' +import { createDesktopPublicationRecord } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-record.ts' +import { readRetainedDesktopManifest, type DesktopRetainedManifest } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' +import { resolveRetainedDesktopPublication } from '@deepseek-ai/dsh-desktop-publisher/resolve-retained-desktop-publish-ci.ts' +import type { DesktopPublishEvent, DesktopRemoteObject, DesktopPublishTransport } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts' const digest = (contents: string) => ({ size: Buffer.byteLength(contents), sha512: createHash('sha512').update(contents).digest('base64'), @@ -284,7 +284,7 @@ it('runs the real route CLI without gh and emits the selected route and preset', routes: { runner: { label: 'dsh-runner', target: 'mac-arm64' } }, } const result = await promisify(execFile)(process.execPath, - ['--import', 'tsx/esm', 'apps/desktop/scripts/publish-desktop-rollout-ci.ts', 'route'], { + ['--import', 'tsx/esm', 'apps/desktop-publisher/src/publish-desktop-rollout-ci.ts', 'route'], { timeout: 30_000, env: { ...Object.fromEntries(Object.entries(process.env).filter(([key]) => key.toLowerCase() !== 'path')), PATH: '', GH_TOKEN: 'fixture-token', GITHUB_API_URL: `http://127.0.0.1:${address.port}`, GITHUB_OUTPUT: output, @@ -403,6 +403,6 @@ it('executes the master guard and keeps all rollout preflights ahead of dependen if (name === 'route') continue const local = job.steps.findIndex(step => step.run?.includes('preflight-desktop-publish-local.mjs')) expect(local).toBeGreaterThanOrEqual(0) - expect(local).toBeLessThan(job.steps.findIndex(step => step.run === 'pnpm install --frozen-lockfile')) + expect(local).toBeLessThan(job.steps.findIndex(step => step.run === 'pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts')) } }) diff --git a/apps/desktop/tests/desktop-upload-plan.spec.ts b/apps/desktop/tests/desktop-upload-plan.spec.ts index 0d9e90f00d..144b249fb4 100644 --- a/apps/desktop/tests/desktop-upload-plan.spec.ts +++ b/apps/desktop/tests/desktop-upload-plan.spec.ts @@ -6,11 +6,11 @@ import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { load } from 'js-yaml' import { createDesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' -import { desktopUpdateMetadataFilename } from '../scripts/desktop-auto-update-environment.mjs' +import { desktopUpdateMetadataFilename } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import type { DesktopPackageTargetName } from '../scripts/package-target.ts' -import { createDesktopCos } from '../scripts/desktop-cos.ts' +import { createDesktopCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import { uploadDesktopRelease } from '../scripts/desktop-upload-run.ts' -import { startCosLoopback } from './cos-loopback.ts' +import { startCosLoopback } from '../../desktop-publisher/tests/cos-loopback.ts' const temporaryDirectories: string[] = [] const TEST_ORIGIN = 'https://desktop-updates.example.com' diff --git a/apps/desktop/tests/desktop-upload-run.spec.ts b/apps/desktop/tests/desktop-upload-run.spec.ts index 2bbe2a66ab..d3e26bf25b 100644 --- a/apps/desktop/tests/desktop-upload-run.spec.ts +++ b/apps/desktop/tests/desktop-upload-run.spec.ts @@ -4,10 +4,10 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import COS from 'cos-nodejs-sdk-v5' import { afterEach, describe, expect, it } from 'vitest' -import { createDesktopCos, DESKTOP_COS_REGION } from '../scripts/desktop-cos.ts' +import { createDesktopCos, DESKTOP_COS_REGION } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import { uploadDesktopRelease } from '../scripts/desktop-upload-run.ts' import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' -import { answer, cosError, startCosLoopback, type CosLoopback, type CosLoopbackRequest } from './cos-loopback.ts' +import { answer, cosError, startCosLoopback, type CosLoopback, type CosLoopbackRequest } from '../../desktop-publisher/tests/cos-loopback.ts' const roots: string[] = [] const loopbacks: CosLoopback[] = [] @@ -107,7 +107,7 @@ describe('release upload audit with the real COS SDK and an isolated loopback or expect(plan.sourceSha256['upload-target.ts']).toBe(createHash('sha256') .update(await readFile(join(import.meta.dirname, '../scripts/upload-target.ts'))).digest('hex')) expect(plan.sourceSha256['desktop-cos.ts']).toBe(createHash('sha256') - .update(await readFile(join(import.meta.dirname, '../scripts/desktop-cos.ts'))).digest('hex')) + .update(await readFile(join(import.meta.dirname, '../../desktop-publisher/src/desktop-cos.ts'))).digest('hex')) const result = await json(join(directory, 'result.json')) expect(result).toMatchObject({ success: true, stage: 'complete', confirmedPuts: 2, publicReadback: 'not-performed' }) const events = await journal(join(directory, 'events.jsonl')) diff --git a/apps/desktop/tests/installed-update-cos.spec.ts b/apps/desktop/tests/installed-update-cos.spec.ts index ca8dd93ec0..81f9006c4f 100644 --- a/apps/desktop/tests/installed-update-cos.spec.ts +++ b/apps/desktop/tests/installed-update-cos.spec.ts @@ -5,7 +5,7 @@ import { join } from 'node:path' import type COS from 'cos-nodejs-sdk-v5' import { afterEach, describe, expect, it, vi } from 'vitest' import { createInstalledUpdateCos } from '../scripts/installed-update-cos.ts' -import { answer, cosError, startCosLoopback, type CosLoopback, type CosLoopbackResponder } from './cos-loopback.ts' +import { answer, cosError, startCosLoopback, type CosLoopback, type CosLoopbackResponder } from '../../desktop-publisher/tests/cos-loopback.ts' const state = vi.hoisted(() => ({ settings: 'test', @@ -18,8 +18,8 @@ vi.mock('../scripts/desktop-package-environment.mjs', () => ({ loadDesktopPackag DOWNLOAD_TEST_COS_SECRET_KEY: 'fixture-key', DSH_DESKTOP_WINDOWS_TOKEN_PIN: 'fixture-pin-not-for-sdk', }) })) -vi.mock('../scripts/desktop-cos.ts', async (original) => { - const actual = await original() +vi.mock('@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts', async (original) => { + const actual = await original() return { ...actual, createDesktopCos: (credentials: Parameters[0]) => { const cos = actual.createDesktopCos(credentials) state.redirect?.(cos) diff --git a/apps/desktop/tests/purge-command.spec.ts b/apps/desktop/tests/purge-command.spec.ts index a690db7a35..9b826b0830 100644 --- a/apps/desktop/tests/purge-command.spec.ts +++ b/apps/desktop/tests/purge-command.spec.ts @@ -30,8 +30,10 @@ it('forwards the documented pnpm purge command through both package scripts to t for (const dependency of ['.bin', 'pnpm', 'tsx', 'semver']) { await symlink(join(root, 'node_modules', dependency), join(directory, 'node_modules', dependency), 'junction') } + await mkdir(join(directory, 'node_modules/@deepseek-ai'), { recursive: true }) + await symlink(join(root, 'apps/desktop-publisher'), join(directory, 'node_modules/@deepseek-ai/dsh-desktop-publisher'), 'junction') await copyFile(join(root, 'apps/desktop/scripts/upload-target.ts'), join(scripts, 'upload-target.ts')) - for (const filename of ['desktop-auto-update-environment.mjs', 'desktop-build-paths.mjs']) { + for (const filename of ['desktop-build-paths.mjs']) { await copyFile(join(root, 'apps/desktop/scripts', filename), join(scripts, filename)) } // Only command forwarding and parsing are under test; all external work fails closed. diff --git a/apps/desktop/tests/retain-desktop-ci.spec.ts b/apps/desktop/tests/retain-desktop-ci.spec.ts index fdddcdf451..48d204e522 100644 --- a/apps/desktop/tests/retain-desktop-ci.spec.ts +++ b/apps/desktop/tests/retain-desktop-ci.spec.ts @@ -5,7 +5,7 @@ import { join } from 'node:path' import { unzipSync } from 'fflate' import { afterEach, expect, it } from 'vitest' import { desktopReleasesRoot, retainDesktopCi, resolveDesktopRetentionRunner } from '../scripts/retain-desktop-ci.ts' -import { verifyRetainedDesktopRelease } from '../scripts/desktop-release-store.ts' +import { verifyRetainedDesktopRelease } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' import { verifyDesktopArchive } from '../scripts/archive-desktop-ci.ts' import { prepareDesktopPublication } from '../scripts/publish-desktop-ci.ts' diff --git a/apps/desktop/tests/upload-target.spec.ts b/apps/desktop/tests/upload-target.spec.ts index 94e9aa5b4f..fa62fbf9d2 100644 --- a/apps/desktop/tests/upload-target.spec.ts +++ b/apps/desktop/tests/upload-target.spec.ts @@ -13,7 +13,7 @@ vi.mock('../scripts/desktop-edgeone.ts', async importOriginal => ({ vi.mock('../scripts/desktop-package-environment.mjs', () => ({ loadDesktopPackageEnvironment: vi.fn() })) vi.mock('../scripts/desktop-upload-plan.ts', () => ({ createDesktopUploadPlan: vi.fn() })) -vi.mock('../scripts/desktop-cos.ts', () => ({ createDesktopCos: vi.fn() })) +vi.mock('@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts', () => ({ createDesktopCos: vi.fn() })) vi.mock('../scripts/desktop-upload-run.ts', () => ({ uploadDesktopRelease: vi.fn() })) vi.mock('../scripts/desktop-release-tag.ts', async importOriginal => ({ ...await importOriginal(), diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 718a239832..8057f54080 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -734,6 +734,9 @@ importers: specifier: ^8.21.3 version: 8.21.3 devDependencies: + '@deepseek-ai/dsh-desktop-publisher': + specifier: workspace:* + version: link:../desktop-publisher '@deepseek-ai/dsh-app-boot': specifier: workspace:* version: link:../../packages/boot/app-boot @@ -843,6 +846,27 @@ importers: specifier: 4.6.6 version: 4.6.6 + apps/desktop-publisher: + dependencies: + zod: + specifier: 4.6.6 + version: 4.6.6 + js-yaml: + specifier: ^4.3.2 + version: 4.3.2 + semver: + specifier: ^7.8.5 + version: 7.8.5 + cos-nodejs-sdk-v5: + specifier: 3.0.0 + version: 3.0.0 + tencentcloud-sdk-nodejs-teo: + specifier: 4.1.330 + version: 4.1.330(supports-color@9.4.0) + tsx: + specifier: ^4.23.13 + version: 4.23.13 + apps/desktop-host: dependencies: '@deepseek-ai/cordis': diff --git a/scripts/check-workspace-constraints.spec.ts b/scripts/check-workspace-constraints.spec.ts index a06ff702c2..eb03f5fe29 100644 --- a/scripts/check-workspace-constraints.spec.ts +++ b/scripts/check-workspace-constraints.spec.ts @@ -436,8 +436,7 @@ describe('package payload constraints', () => { }, ) - it('exempts the private plugin market generator from release rules in its own directory only', () => { - const dir = 'apps/plugin-market-generator' + it.each(['apps/plugin-market-generator', 'apps/desktop-publisher'])('exempts private tool %s from release rules in its own directory only', (dir) => { const manifest = JSON.parse(readFileSync(new URL(`../${dir}/package.json`, import.meta.url), 'utf8')) as WorkspaceManifest['manifest'] expect(checkWorkspaceManifest({ dir, manifest })).toEqual([]) expect(checkWorkspaceManifest({ dir: 'apps/other-tool', manifest })).not.toEqual([]) diff --git a/scripts/check-workspace-constraints.ts b/scripts/check-workspace-constraints.ts index 5356dba419..d13b0324e0 100644 --- a/scripts/check-workspace-constraints.ts +++ b/scripts/check-workspace-constraints.ts @@ -63,12 +63,14 @@ const publishedRepositoryUrl = 'git+https://github.com/deepseek-ai/deepseek-harn const experimentalPackageDirectory = /^packages\/experimental\/[^/]+$/ /** Private reference tool run from the repository; it publishes no files. */ const pluginMarketGeneratorDirectory = 'apps/plugin-market-generator' +/** Source-only private release tool, sharing the Desktop version. */ +const desktopPublisherDirectory = 'apps/desktop-publisher' /** * Ordinary directories whose packages this repository publishes: one release member each. The reference plugin * market generator is a private repository tool, not a published application. */ const standardReleaseMemberDirectory = new RegExp( - `^(?:packages/(?!experimental/)[^/]+/[^/]+|apps/(?!desktop(?:-host)?$|${pluginMarketGeneratorDirectory.slice('apps/'.length)}$)[^/]+|vendor/[^/]+)$`, + `^(?:packages/(?!experimental/)[^/]+/[^/]+|apps/(?!desktop(?:-host)?$|${pluginMarketGeneratorDirectory.slice('apps/'.length)}$|${desktopPublisherDirectory.slice('apps/'.length)}$)[^/]+|vendor/[^/]+)$`, 'u', ) /** Installable application assembled by electron-builder rather than published to npm. */ @@ -558,7 +560,7 @@ export function checkWorkspaceManifest({ dir, manifest }: WorkspaceManifest): st return errors } - if (dir.startsWith('apps/') && dir !== desktopApplicationDirectory && dir !== pluginMarketGeneratorDirectory && manifest.name?.startsWith('@deepseek-ai/')) { + if (dir.startsWith('apps/') && dir !== desktopApplicationDirectory && dir !== pluginMarketGeneratorDirectory && dir !== desktopPublisherDirectory && manifest.name?.startsWith('@deepseek-ai/')) { const expectedFiles = appPackageFiles[manifest.name] if (expectedFiles === undefined) { errors.push(`${label}: app package has no publication files policy`) diff --git a/scripts/desktop-publish-workflow.spec.ts b/scripts/desktop-publish-workflow.spec.ts index f6dfa1c4f4..26df0d6b73 100644 --- a/scripts/desktop-publish-workflow.spec.ts +++ b/scripts/desktop-publish-workflow.spec.ts @@ -97,7 +97,7 @@ it('defaults to production website upload and separates cache-only recovery', () expect(preflight).toBeLessThan(job.steps.findIndex(step => step.run === 'pnpm install --frozen-lockfile')) expect(job.env?.DESKTOP_WEBSITE_APPROVAL).toBe('${{ needs.prepare.outputs.website-approval }}') } - expect(upload.steps.find(step => step.id === 'website')?.run).toBe('node --import tsx apps/desktop/scripts/publish-website-ci.ts upload') - expect(purge.steps.find(step => step.id === 'website')?.run).toBe('node --import tsx apps/desktop/scripts/publish-website-ci.ts purge') + expect(upload.steps.find(step => step.id === 'website')?.run).toBe('node --import tsx apps/desktop-publisher/src/publish-website-ci.ts upload') + expect(purge.steps.find(step => step.id === 'website')?.run).toBe('node --import tsx apps/desktop-publisher/src/publish-website-ci.ts purge') expect(purge.steps.some(step => step.run?.includes('publish-desktop-ci.ts'))).toBe(false) }) diff --git a/tsconfig.base.json b/tsconfig.base.json index 1429e8389a..7208c7f37e 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -28,6 +28,7 @@ // not declaration path aliases, keep each package/vendor source compiled // under its own tsconfig boundary. "paths": { + "@deepseek-ai/dsh-desktop-publisher/*": ["./apps/desktop-publisher/src/*"], "@deepseek-ai/dsh-client-ui-file-actions": ["./packages/client/ui-file-actions/src/index.ts"], "@deepseek-ai/dsh-client-ui-file-actions/client": ["./packages/client/ui-file-actions/src/client/index.ts"], "@deepseek-ai/dsh-client-ui-file-actions/types": ["./packages/client/ui-file-actions/src/types.ts"], diff --git a/tsconfig.host.json b/tsconfig.host.json index 51393074e9..3465ad1e16 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -245,6 +245,8 @@ "apps/cli/tests/**/*.ts", "apps/plugin-market-generator/tests/**/*.ts", "apps/desktop/scripts/**/*.ts", + "apps/desktop-publisher/src/**/*.ts", + "apps/desktop-publisher/tests/**/*.ts", "apps/desktop/tests/**/*.ts", "apps/desktop-host/tests/**/*.ts", "benchmarks/**/*.ts", From 96ce46c3d18ca464c8d82098b8831c6e1f82be7c Mon Sep 17 00:00:00 2001 From: LegGasai Date: Thu, 5 Nov 2026 17:27:28 +0800 Subject: [PATCH 007/450] fix(web): use the menu corner radius for the Session panel --- .../client/ui-session-panel/src/client/SessionPanel.module.css | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/client/ui-session-panel/src/client/SessionPanel.module.css b/packages/client/ui-session-panel/src/client/SessionPanel.module.css index f3bc08665e..8bd6ca6fa8 100644 --- a/packages/client/ui-session-panel/src/client/SessionPanel.module.css +++ b/packages/client/ui-session-panel/src/client/SessionPanel.module.css @@ -16,7 +16,8 @@ overscroll-behavior: contain; padding: 6px 8px; border: 0; - border-radius: var(--dsw-radius-panel); + /* The standard menu tier: a compact summary surface, not an enclosing panel. */ + border-radius: var(--dsw-radius-lg); color: var(--dsw-alias-label-primary); background: var(--dsw-alias-bg-layer-1); box-shadow: var(--dsw-elevation-panel); From 939d83ab9c4be2f2c3c0fbb3dd8f9734d292ba5b Mon Sep 17 00:00:00 2001 From: winewill Date: Thu, 5 Nov 2026 17:45:31 +0800 Subject: [PATCH 008/450] fix(desktop): validate isolated publisher entrypoints and checkout boundaries --- .github/AGENTS.md | 2 +- .github/workflows/ci-windows.yml | 35 +++++++++++- .github/workflows/ci.yml | 37 ++++++++++++- .github/workflows/desktop-publish.yml | 10 ++-- .github/workflows/desktop-publisher-check.yml | 35 ------------ .github/workflows/desktop-rollout.yml | 54 +++++++++---------- THIRD_PARTY_NOTICES.md | 4 +- apps/desktop-publisher/README.i18n.yaml | 28 ++++++++++ apps/desktop-publisher/README.md | 49 +++++++++++++++++ apps/desktop-publisher/README.zh.md | 49 +++++++++++++++++ .../src/desktop-upload-types.ts | 1 - .../preflight-desktop-publish-local.d.mts | 0 .../src}/preflight-desktop-publish-local.mjs | 0 .../src}/preflight-desktop-publish.d.mts | 0 .../src}/preflight-desktop-publish.mjs | 2 +- .../tests/desktop-publication-failure.spec.ts | 2 +- .../tests/isolated-install.mjs | 2 +- apps/desktop-publisher/tests/preinstall.mjs | 32 +++++++++++ apps/desktop-publisher/tests/workflow.spec.ts | 29 +++++++++- apps/desktop/README.i18n.yaml | 4 +- apps/desktop/README.md | 1 + apps/desktop/README.zh.md | 1 + apps/desktop/scripts/desktop-edgeone.ts | 2 +- apps/desktop/scripts/desktop-upload-plan.ts | 8 +-- apps/desktop/scripts/desktop-upload-run.ts | 13 +++-- apps/desktop/scripts/retain-desktop-ci.ts | 6 +-- .../desktop-publish-local-preflight.spec.ts | 6 +-- .../tests/desktop-publish-preflight.spec.ts | 2 +- apps/desktop/tests/desktop-rollout.spec.ts | 2 +- apps/desktop/tests/desktop-upload-run.spec.ts | 1 + .../tests/installed-update-cos.spec.ts | 1 + apps/desktop/tests/purge-command.spec.ts | 7 ++- pnpm-lock.yaml | 48 ++++++++--------- scripts/desktop-publish-workflow.spec.ts | 4 +- 34 files changed, 351 insertions(+), 126 deletions(-) delete mode 100644 .github/workflows/desktop-publisher-check.yml create mode 100644 apps/desktop-publisher/README.i18n.yaml create mode 100644 apps/desktop-publisher/README.md create mode 100644 apps/desktop-publisher/README.zh.md rename apps/{desktop/scripts => desktop-publisher/src}/preflight-desktop-publish-local.d.mts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/preflight-desktop-publish-local.mjs (100%) rename apps/{desktop/scripts => desktop-publisher/src}/preflight-desktop-publish.d.mts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/preflight-desktop-publish.mjs (96%) create mode 100644 apps/desktop-publisher/tests/preinstall.mjs diff --git a/.github/AGENTS.md b/.github/AGENTS.md index 733b45dac2..ffef007a51 100644 --- a/.github/AGENTS.md +++ b/.github/AGENTS.md @@ -8,4 +8,4 @@ The merge checks run from three workflows named `Policy`, which run on `pull_req The manual Desktop publication workflow selects the original successful `package` job attempt independently of `upload-artifact` archival status, then routes each retained build through `DESKTOP_PUBLISH_RUNNERS` to its original machine's unique label. Keep Windows run steps on native PowerShell and Mac run steps on the default POSIX shell; shared entrypoints are Node scripts. Test and production jobs use separate `desktop-test` and `desktop-production` approval Environments after a credential-free preparation job. -`Publish Desktop · Rollout & Website` reuses the same original-machine routing and approval Environments. Its preparation reads retained metadata and initial publication evidence without revalidating package binaries; it does not create release tags. Cache-only recovery uses the existing website approval and upload journal. +`Publish Desktop · Rollout & Website` reuses the same original-machine routing and approval Environments. Its preparation reads retained metadata and initial publication evidence without revalidating package binaries; it does not create release tags. Cache-only recovery uses the existing website approval and upload journal. Rollout installs only publisher production dependencies in `desktop-rollout` and `website-rollout` checkouts; do not reuse the full-install publication checkouts. Both publication workflows run dependency-free preflights from `apps/desktop-publisher/src`. The required CI verdicts include isolated publisher installation checks: Linux/macOS in `ci.yml`, native Windows in `ci-windows.yml`. diff --git a/.github/workflows/ci-windows.yml b/.github/workflows/ci-windows.yml index 47ba28681e..142f4dfbd9 100644 --- a/.github/workflows/ci-windows.yml +++ b/.github/workflows/ci-windows.yml @@ -23,6 +23,39 @@ concurrency: cancel-in-progress: true jobs: + windows-publisher: + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-2vcpu-windows-2025' + || vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted' + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "dsh-win-ci", "windows"]') + || 'dsh-windows-2025-16core' }} + defaults: + run: + shell: pwsh + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + path: publisher-isolated + - uses: actions/setup-node@v7.0.0 + with: + node-version: '24' + - name: Check preflights before dependency installation + working-directory: publisher-isolated + run: node apps/desktop-publisher/tests/preinstall.mjs + - uses: pnpm/action-setup@v5.0.0 + with: + package_json_file: publisher-isolated/package.json + dest: ${{ runner.temp }}/setup-pnpm-publisher-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} + - name: Install only publisher production dependencies + working-directory: publisher-isolated + run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts + - name: Load publisher without Desktop or root development dependencies + working-directory: publisher-isolated/apps/desktop-publisher + run: node --import tsx tests/isolated-install.mjs + # Native builds and process tests block pull requests independently of coverage. # Observational checks reuse the successful build and remain non-blocking. # Dependabot PRs are excluded from the self-hosted pool and stay queued for @@ -258,7 +291,7 @@ jobs: && github.event.pull_request.user.login != 'dependabot[bot]' && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') || 'ubuntu-latest' }} - needs: [windows-build, windows-native-tests] + needs: [windows-publisher, windows-build, windows-native-tests] if: ${{ !cancelled() && github.event_name == 'pull_request' }} steps: - name: Fail if any needed job did not succeed diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 916971cfa4..d74e2355e0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,6 +19,41 @@ concurrency: cancel-in-progress: true jobs: + publisher-isolated: + strategy: + fail-fast: false + matrix: + os: [linux, macos] + runs-on: >- + ${{ matrix.os == 'macos' && 'macos-latest' + || vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-4vcpu-ubuntu-2404' + || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') + || 'ubuntu-latest' }} + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + path: publisher-isolated + - uses: actions/setup-node@v7.0.0 + with: + node-version: '24' + - name: Check preflights before dependency installation + working-directory: publisher-isolated + run: node apps/desktop-publisher/tests/preinstall.mjs + - uses: pnpm/action-setup@v5.0.0 + with: + package_json_file: publisher-isolated/package.json + dest: ${{ runner.temp }}/setup-pnpm-publisher-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} + - name: Install only publisher production dependencies + working-directory: publisher-isolated + run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts + - name: Load publisher without Desktop or root development dependencies + working-directory: publisher-isolated/apps/desktop-publisher + run: node --import tsx tests/isolated-install.mjs + # Three enterprise jobs isolate coverage, static analysis, and the # build-backed consumer tail. The consumer job owns the only Linux build so @@ -572,7 +607,7 @@ jobs: && github.event.pull_request.user.login != 'dependabot[bot]' && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') || 'ubuntu-latest' }} - needs: [node-24, node-24-coverage, node-24-lint, node-24-bench, node-24-consumers, node-compat] + needs: [publisher-isolated, node-24, node-24-coverage, node-24-lint, node-24-bench, node-24-consumers, node-compat] if: ${{ !cancelled() && github.event_name == 'pull_request' }} steps: - name: Fail if any needed job did not succeed diff --git a/.github/workflows/desktop-publish.yml b/.github/workflows/desktop-publish.yml index 8a1fa4d79d..030a4cb63b 100644 --- a/.github/workflows/desktop-publish.yml +++ b/.github/workflows/desktop-publish.yml @@ -45,7 +45,7 @@ jobs: id: preflight env: GH_TOKEN: ${{ github.token }} - run: node apps/desktop/scripts/preflight-desktop-publish.mjs + run: node apps/desktop-publisher/src/preflight-desktop-publish.mjs - uses: pnpm/action-setup@v5.0.0 - uses: actions/setup-node@v7.0.0 with: @@ -91,7 +91,7 @@ jobs: node-version: '24' - name: Check local publication configuration before dependency installation working-directory: desktop-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm install --frozen-lockfile working-directory: desktop-publisher - name: Resolve retained package and approval environment @@ -136,7 +136,7 @@ jobs: node-version: '24' - name: Check local publication configuration before dependency installation working-directory: desktop-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm install --frozen-lockfile working-directory: desktop-publisher - name: Verify local package without upload credentials @@ -204,7 +204,7 @@ jobs: node-version: '24' - name: Check local publication configuration working-directory: website-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm install --frozen-lockfile working-directory: website-publisher - name: Upload website installer @@ -249,7 +249,7 @@ jobs: node-version: '24' - name: Check local publication configuration working-directory: website-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm install --frozen-lockfile working-directory: website-publisher - name: Recover and observe website cache purge diff --git a/.github/workflows/desktop-publisher-check.yml b/.github/workflows/desktop-publisher-check.yml deleted file mode 100644 index 37ad3220d2..0000000000 --- a/.github/workflows/desktop-publisher-check.yml +++ /dev/null @@ -1,35 +0,0 @@ -name: Verify Desktop Publisher -on: - pull_request: - paths: - - 'apps/desktop-publisher/**' - - 'apps/desktop/**' - - 'package.json' - - 'pnpm-lock.yaml' - - 'pnpm-workspace.yaml' - - '.github/workflows/desktop-publisher-check.yml' - - '.github/workflows/desktop-rollout.yml' - workflow_dispatch: -permissions: - contents: read -jobs: - isolated-install: - strategy: - fail-fast: false - matrix: - os: [ubuntu-latest, macos-latest, windows-latest] - runs-on: ${{ matrix.os }} - timeout-minutes: 15 - steps: - - uses: actions/checkout@v7.0.1 - with: - persist-credentials: false - - uses: pnpm/action-setup@v5.0.0 - - uses: actions/setup-node@v7.0.0 - with: - node-version: '24' - - name: Install only publisher production dependencies - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts - - name: Load publisher without the Desktop or root development dependencies - working-directory: apps/desktop-publisher - run: node --import tsx tests/isolated-install.mjs diff --git a/.github/workflows/desktop-rollout.yml b/.github/workflows/desktop-rollout.yml index 80932b63f2..f2e6bec6d8 100644 --- a/.github/workflows/desktop-rollout.yml +++ b/.github/workflows/desktop-rollout.yml @@ -45,7 +45,7 @@ jobs: id: preflight env: GH_TOKEN: ${{ github.token }} - run: node apps/desktop/scripts/preflight-desktop-publish.mjs + run: node apps/desktop-publisher/src/preflight-desktop-publish.mjs - uses: pnpm/action-setup@v5.0.0 - uses: actions/setup-node@v7.0.0 with: @@ -82,28 +82,28 @@ jobs: with: persist-credentials: false clean: false - path: desktop-publisher + path: desktop-rollout - uses: pnpm/action-setup@v5.0.0 with: - package_json_file: desktop-publisher/package.json + package_json_file: desktop-rollout/package.json dest: ${{ runner.temp }}/publish-pnpm-${{ github.run_id }}-${{ github.run_attempt }} - uses: actions/setup-node@v7.0.0 with: node-version: '24' - name: Check local publication configuration before dependency installation - working-directory: desktop-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + working-directory: desktop-rollout + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts - working-directory: desktop-publisher + working-directory: desktop-rollout - name: Resolve retained package and approval environment id: local - working-directory: desktop-publisher/apps/desktop-publisher + working-directory: desktop-rollout/apps/desktop-publisher env: GH_TOKEN: ${{ github.token }} run: node --import tsx src/publish-desktop-rollout-ci.ts route - name: Verify initial publication and metadata without upload credentials id: check - working-directory: desktop-publisher/apps/desktop-publisher + working-directory: desktop-rollout/apps/desktop-publisher env: DESKTOP_PUBLISH_ROUTE: ${{ steps.local.outputs.route }} run: node --import tsx src/publish-desktop-rollout-ci.ts check @@ -129,26 +129,26 @@ jobs: with: persist-credentials: false clean: false - path: desktop-publisher + path: desktop-rollout - uses: pnpm/action-setup@v5.0.0 with: - package_json_file: desktop-publisher/package.json + package_json_file: desktop-rollout/package.json dest: ${{ runner.temp }}/publish-pnpm-${{ github.run_id }}-${{ github.run_attempt }} - uses: actions/setup-node@v7.0.0 with: node-version: '24' - name: Check local publication configuration before dependency installation - working-directory: desktop-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + working-directory: desktop-rollout + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts - working-directory: desktop-publisher + working-directory: desktop-rollout - name: Verify initial publication and metadata without upload credentials id: check - working-directory: desktop-publisher/apps/desktop-publisher + working-directory: desktop-rollout/apps/desktop-publisher run: node --import tsx src/publish-desktop-rollout-ci.ts check - name: Apply rollout to the published feed id: publish - working-directory: desktop-publisher/apps/desktop-publisher + working-directory: desktop-rollout/apps/desktop-publisher run: node --import tsx src/publish-desktop-rollout-ci.ts apply - name: Retain publication audit continue-on-error: true @@ -181,22 +181,22 @@ jobs: with: persist-credentials: false clean: false - path: website-publisher + path: website-rollout - uses: pnpm/action-setup@v5.0.0 with: - package_json_file: website-publisher/package.json + package_json_file: website-rollout/package.json dest: ${{ runner.temp }}/website-pnpm-${{ github.run_id }}-${{ github.run_attempt }} - uses: actions/setup-node@v7.0.0 with: node-version: '24' - name: Check local publication configuration - working-directory: website-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + working-directory: website-rollout + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts - working-directory: website-publisher + working-directory: website-rollout - name: Upload website installer id: website - working-directory: website-publisher/apps/desktop-publisher + working-directory: website-rollout/apps/desktop-publisher run: node --import tsx src/publish-desktop-rollout-ci.ts website-upload - name: Archive website feed verification if: always() && steps.website.outputs.rollout-record != '' @@ -236,22 +236,22 @@ jobs: with: persist-credentials: false clean: false - path: website-publisher + path: website-rollout - uses: pnpm/action-setup@v5.0.0 with: - package_json_file: website-publisher/package.json + package_json_file: website-rollout/package.json dest: ${{ runner.temp }}/website-pnpm-${{ github.run_id }}-${{ github.run_attempt }} - uses: actions/setup-node@v7.0.0 with: node-version: '24' - name: Check local publication configuration - working-directory: website-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + working-directory: website-rollout + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts - working-directory: website-publisher + working-directory: website-rollout - name: Recover and observe website cache purge id: website - working-directory: website-publisher/apps/desktop-publisher + working-directory: website-rollout/apps/desktop-publisher run: node --import tsx src/publish-desktop-rollout-ci.ts website-purge - name: Archive website publication diagnostics if: always() && steps.website.outputs.record != '' diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index c38e1a3cea..b932fe3827 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -87,6 +87,7 @@ External packages installed for runtime use or embedded in distributed Host or b | [`clsx`](https://github.com/lukeed/clsx) | MIT | | [`commander`](https://github.com/tj/commander.js) | MIT | | [`compression`](https://github.com/expressjs/compression) | MIT | +| [`cos-nodejs-sdk-v5`](https://github.com/tencentyun/cos-nodejs-sdk-v5) | ISC | | [`cross-spawn`](https://github.com/moxystudio/node-cross-spawn) | MIT | | [`diff`](https://github.com/kpdecker/jsdiff) | BSD-3-Clause | | [`dompurify`](https://github.com/cure53/DOMPurify) | (MPL-2.0 OR Apache-2.0) | @@ -144,6 +145,7 @@ External packages installed for runtime use or embedded in distributed Host or b | [`string_decoder`](https://github.com/nodejs/string_decoder) | MIT | | [`supports-color`](https://github.com/chalk/supports-color) | MIT | | [`tar`](https://github.com/isaacs/node-tar) | BlueOak-1.0.0 | +| [`tencentcloud-sdk-nodejs-teo`](https://github.com/tencentcloud/tencentcloud-sdk-nodejs) | Apache-2.0 | | [`tsx`](https://github.com/privatenumber/tsx) | MIT | | [`turndown`](https://github.com/mixmark-io/turndown) | MIT | | [`typescript`](https://github.com/microsoft/TypeScript) | Apache-2.0 | @@ -247,7 +249,6 @@ External packages **directly declared** for development, tests, types, or toolin | [`@yao-pkg/pkg`](https://github.com/yao-pkg/pkg) | MIT | | [`@yarnpkg/cli-dist`](https://github.com/yarnpkg/berry) | BSD-2-Clause | | [`app-builder-lib`](https://github.com/electron-userland/electron-builder) | MIT | -| [`cos-nodejs-sdk-v5`](https://github.com/tencentyun/cos-nodejs-sdk-v5) | ISC | | [`cytoscape`](https://github.com/cytoscape/cytoscape.js) | MIT | | [`cytoscape-cose-bilkent`](https://github.com/cytoscape/cytoscape.js-cose-bilkent) | MIT | | [`dayjs`](https://github.com/iamkun/dayjs) | MIT | @@ -274,7 +275,6 @@ External packages **directly declared** for development, tests, types, or toolin | [`selfsigned`](https://github.com/jfromaniello/selfsigned) | MIT | | [`smol-toml`](https://github.com/squirrelchat/smol-toml) | BSD-3-Clause | | [`spdx-expression-parse`](https://github.com/jslicense/spdx-expression-parse.js) | MIT | -| [`tencentcloud-sdk-nodejs-teo`](https://github.com/tencentcloud/tencentcloud-sdk-nodejs) | Apache-2.0 | | [`tsdown`](https://github.com/rolldown/tsdown) | MIT | | [`typescript-language-server`](https://github.com/typescript-language-server/typescript-language-server) | Apache-2.0 | | [`vite`](https://github.com/vitejs/vite) | MIT | diff --git a/apps/desktop-publisher/README.i18n.yaml b/apps/desktop-publisher/README.i18n.yaml new file mode 100644 index 0000000000..c95af89587 --- /dev/null +++ b/apps/desktop-publisher/README.i18n.yaml @@ -0,0 +1,28 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write apps/desktop-publisher/README.md +/: + en: b6cea27035a6acd8 + zh: c8484ea772e48b76 +/desktop-publisher: + en: 2f3214a4c5f468bd + zh: 0344414f601ce5da +/desktop-publisher/summary: + en: 96e01061bb58ef81 + zh: 34e3e9da3adbdfef +/desktop-publisher/table-of-contents: + en: c910eb62c99ebaae + zh: a39d3e1344eb1b3d +/desktop-publisher/use-this-package: + en: 9678d489d32b9e7b + zh: 6d0ddae4cf96db94 +/desktop-publisher/implementation: + en: 62a7d718a25d4ea4 + zh: 10c8e93749810a15 +/desktop-publisher/limitations: + en: cc71e293492ce240 + zh: 1b9388bf9b108274 +/desktop-publisher/limitations/dev-note: + en: 0a1253c6f7b5e8b9 + zh: 9f56528562c7c914 diff --git a/apps/desktop-publisher/README.md b/apps/desktop-publisher/README.md new file mode 100644 index 0000000000..e4724165b7 --- /dev/null +++ b/apps/desktop-publisher/README.md @@ -0,0 +1,49 @@ +--- +description: "Run Desktop publication and staged rollout from retained packages without installing Desktop build dependencies." +kind: "package-library" +--- +# Desktop publisher + +English | [中文](README.zh.md) + +## Summary + +Publish retained Desktop packages, change an existing release's rollout percentage, and refresh website installers. The manual GitHub workflows select the original packaging machine and require the configured environment approvals. This private workspace shares the repository lockfile and runs TypeScript source directly with Node 24 and tsx. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Implementation](#implementation) +- [Limitations](#limitations) + +## Use this package + +Use [Publish Desktop](../../.github/workflows/desktop-publish.yml) for initial publication and [Rollout & Website](../../.github/workflows/desktop-rollout.yml) for an already published version. The workflows own operator inputs, runner routing, credentials, and approval steps. Rollout installs only this workspace's production dependencies with lifecycle scripts disabled; invoke its entrypoints with Node from this package directory to avoid pnpm's automatic dependency repair. + +The dependency-free preflights run before installation. Their executable regression check is: + +```sh +node apps/desktop-publisher/tests/preinstall.mjs +``` + +## Implementation + +
+Maintainer details + +Desktop build and signing scripts stay in `apps/desktop`; publishing code imports no Desktop implementation. Desktop consumes publisher helpers through the workspace package exports. Runtime dependencies belong in this package's `dependencies`; tests and type checking use repository development tools. The root host TypeScript project checks this source, so there is no separate emitted package or package-local tsconfig. + +Full-install publication and filtered-install rollout use different checkout directories. Changing install modes in one checkout removes development dependency links and can retain stale Desktop directories. Release records live outside these checkouts and remain owned by the existing retained-release configuration. + +Tests under `apps/desktop` may reuse the publisher's loopback COS fixture. Publisher failure tests also exercise the Desktop rollback and archival CLIs as repository integration tests; these test-only paths are not runtime dependencies. The isolated-install CI checks load publisher source without Desktop or root development dependencies on Linux, macOS, and Windows, and contribute to required CI verdicts. + +
+ +## Limitations + +- This private tool is not published to npm and does not generate a standalone artifact. Workflow checkouts must contain the shared lockfile and workspace metadata. +- Isolated-install and preflight tests do not authorize a production write or prove that an installer upgrades a real client. + +### Dev Note + +None. diff --git a/apps/desktop-publisher/README.zh.md b/apps/desktop-publisher/README.zh.md new file mode 100644 index 0000000000..62fcc3dcbf --- /dev/null +++ b/apps/desktop-publisher/README.zh.md @@ -0,0 +1,49 @@ +--- +description: "从保留的安装包执行 Desktop 发布和灰度放量,无需安装 Desktop 构建依赖。" +kind: "package-library" +--- +# Desktop 发布工具 + +[English](README.md) | 中文 + +## 概述 + +发布保留的 Desktop 安装包、调整已发布版本的放量比例,以及刷新官网安装包。手动 GitHub 工作流选择原始打包机器,并要求通过配置的环境审批。此私有 workspace 共用仓库锁文件,通过 Node 24 和 tsx 直接执行 TypeScript 源码。 + +## 目录 + +- [使用此包](#use-this-package) +- [实现](#implementation) +- [限制](#limitations) + +## 使用此包 + +首次发布使用 [Publish Desktop](../../.github/workflows/desktop-publish.yml),已发布版本使用 [Rollout & Website](../../.github/workflows/desktop-rollout.yml)。工作流负责操作输入、运行器路由、凭据和审批步骤。放量仅安装此 workspace 的生产依赖,并禁用生命周期脚本;从此包目录使用 Node 调用入口,避免 pnpm 自动修复依赖。 + +无依赖预检在安装之前运行,其可执行回归检查为: + +```sh +node apps/desktop-publisher/tests/preinstall.mjs +``` + +## 实现 + +
+维护者说明 + +Desktop 构建和签名脚本保留在 `apps/desktop`;发布代码不导入 Desktop 实现。Desktop 通过 workspace 包导出使用发布辅助函数。运行时依赖归此包的 `dependencies` 所有;测试和类型检查使用仓库开发工具。根目录的 host TypeScript 项目检查这些源码,因此没有独立的编译产物或包级 tsconfig。 + +完整安装的发布与筛选安装的放量使用不同 checkout 目录。在同一 checkout 切换安装模式会移除开发依赖链接,也可能保留旧 Desktop 目录。发布记录位于这些 checkout 之外,仍由现有保留版本配置管理。 + +`apps/desktop` 下的测试可以复用发布工具的 loopback COS fixture。发布失败测试还将 Desktop 回滚和归档 CLI 作为仓库集成测试执行;这些测试路径不是运行时依赖。隔离安装 CI 在 Linux、macOS 和 Windows 上验证发布源码无需 Desktop 或根目录开发依赖即可加载,结果纳入必需的 CI 汇总检查。 + +
+ +## 限制 + +- 此私有工具不发布到 npm,也不生成独立产物。工作流 checkout 必须包含共用锁文件和 workspace 元数据。 +- 隔离安装和预检测试不授权生产写入,也不能证明安装包能升级真实客户端。 + +### 开发备注 + +无。 diff --git a/apps/desktop-publisher/src/desktop-upload-types.ts b/apps/desktop-publisher/src/desktop-upload-types.ts index 4faa48b399..48a3982e3a 100644 --- a/apps/desktop-publisher/src/desktop-upload-types.ts +++ b/apps/desktop-publisher/src/desktop-upload-types.ts @@ -31,7 +31,6 @@ export interface DesktopUploadPlan { readonly dirty?: boolean } - /** A publication operation targeting exactly one metadata object or installer. */ export type DesktopSingleUploadPlan = Omit & { readonly artifacts: readonly [DesktopUploadArtifact] diff --git a/apps/desktop/scripts/preflight-desktop-publish-local.d.mts b/apps/desktop-publisher/src/preflight-desktop-publish-local.d.mts similarity index 100% rename from apps/desktop/scripts/preflight-desktop-publish-local.d.mts rename to apps/desktop-publisher/src/preflight-desktop-publish-local.d.mts diff --git a/apps/desktop/scripts/preflight-desktop-publish-local.mjs b/apps/desktop-publisher/src/preflight-desktop-publish-local.mjs similarity index 100% rename from apps/desktop/scripts/preflight-desktop-publish-local.mjs rename to apps/desktop-publisher/src/preflight-desktop-publish-local.mjs diff --git a/apps/desktop/scripts/preflight-desktop-publish.d.mts b/apps/desktop-publisher/src/preflight-desktop-publish.d.mts similarity index 100% rename from apps/desktop/scripts/preflight-desktop-publish.d.mts rename to apps/desktop-publisher/src/preflight-desktop-publish.d.mts diff --git a/apps/desktop/scripts/preflight-desktop-publish.mjs b/apps/desktop-publisher/src/preflight-desktop-publish.mjs similarity index 96% rename from apps/desktop/scripts/preflight-desktop-publish.mjs rename to apps/desktop-publisher/src/preflight-desktop-publish.mjs index 536f3eefa7..fbe6947398 100644 --- a/apps/desktop/scripts/preflight-desktop-publish.mjs +++ b/apps/desktop-publisher/src/preflight-desktop-publish.mjs @@ -2,7 +2,7 @@ import { execFileSync } from 'node:child_process' import { appendFile, readFile } from 'node:fs/promises' import { resolve } from 'node:path' -import { desktopPublishQualificationError } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-qualification.mjs' +import { desktopPublishQualificationError } from './desktop-publish-qualification.mjs' /** * Pin the requested attempt and reject its explicitly named debugging artifacts. diff --git a/apps/desktop-publisher/tests/desktop-publication-failure.spec.ts b/apps/desktop-publisher/tests/desktop-publication-failure.spec.ts index f8ced04f73..b2ab402e2a 100644 --- a/apps/desktop-publisher/tests/desktop-publication-failure.spec.ts +++ b/apps/desktop-publisher/tests/desktop-publication-failure.spec.ts @@ -24,6 +24,7 @@ it('does not retain provider bodies, unknown messages, JSON input or invalid fie expect(desktopPublicationFailure({ code: 'AccessDenied', statusCode: 403 }, 'upload').message).toContain('HTTP 403') }) +// These repository integration tests execute Desktop CLIs; the publisher runtime never imports them. it('prints rollback usage through the real CLI before any audit or remote operation', () => { const result = spawnSync(process.execPath, ['--import', 'tsx/esm', fileURLToPath(new URL('../../desktop/scripts/rollback-desktop-channel.ts', import.meta.url))], { encoding: 'utf8', timeout: 30_000 }) @@ -57,7 +58,6 @@ it('prints structured archival failure through the real CLI', () => { message: 'desktop archival: invalid ZIP output settings' }) }) - it.each(['percentage cannot decrease; inspect the current rollout', 'feed changed before write; inspect and retry', 'written feed is unconfirmed; inspect before retrying'])('retains rollout recovery instructions: %s', (message) => { expect(desktopPublicationFailure(new Error(`desktop rollout: ${message}`), 'desktop rollout')) diff --git a/apps/desktop-publisher/tests/isolated-install.mjs b/apps/desktop-publisher/tests/isolated-install.mjs index 049c56522f..dc4d844c9f 100644 --- a/apps/desktop-publisher/tests/isolated-install.mjs +++ b/apps/desktop-publisher/tests/isolated-install.mjs @@ -1,8 +1,8 @@ /** Run only in a clean checkout after installing this workspace's production dependencies. */ -import '../src/resolve-desktop-publish-ci.ts' import assert from 'node:assert/strict' import { existsSync } from 'node:fs' import { createRequire } from 'node:module' +import '../src/resolve-desktop-publish-ci.ts' import { prepareDesktopRolloutCi } from '../src/publish-desktop-rollout-ci.ts' import { desktopReleasesRoot } from '../src/desktop-releases-root.ts' import { teo } from 'tencentcloud-sdk-nodejs-teo' diff --git a/apps/desktop-publisher/tests/preinstall.mjs b/apps/desktop-publisher/tests/preinstall.mjs new file mode 100644 index 0000000000..17647a5192 --- /dev/null +++ b/apps/desktop-publisher/tests/preinstall.mjs @@ -0,0 +1,32 @@ +/** Exercise the pre-install entrypoints in a fixture with no workspace dependency links. */ +import assert from 'node:assert/strict' +import { spawnSync } from 'node:child_process' +import { copyFile, mkdtemp, realpath, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' + +const directory = await realpath(await mkdtemp(join(tmpdir(), 'publisher-preinstall-'))) +try { + for (const filename of ['preflight-desktop-publish.mjs', 'preflight-desktop-publish-local.mjs', 'desktop-publish-qualification.mjs']) { + await copyFile(new URL(`../src/${filename}`, import.meta.url), join(directory, filename)) + } + const { preflightDesktopPublish } = await import(pathToFileURL(join(directory, 'preflight-desktop-publish.mjs')).href) + assert.equal(preflightDesktopPublish('owner/repo', { package_run_id: '123', package_run_attempt: '2' }, () => [{ artifacts: [] }]), '2') + assert.throws(() => preflightDesktopPublish('owner/repo', { package_run_id: '123', package_run_attempt: '2' }, () => [{ artifacts: [{ name: 'windows-x64-unsigned-123-2' }] }]), /unsigned/) + const env = { ...process.env } + for (const key of ['GITHUB_EVENT_PATH', 'GITHUB_REPOSITORY', 'GITHUB_OUTPUT', 'DSH_PACKAGING_CONFIG_DIR', 'NODE_OPTIONS']) Reflect.deleteProperty(env, key) + for (const [filename, diagnostic] of [ + ['preflight-desktop-publish.mjs', 'Actions context required'], + ['preflight-desktop-publish-local.mjs', 'set DSH_PACKAGING_CONFIG_DIR'], + ]) { + const result = spawnSync(process.execPath, [join(directory, filename)], { env, encoding: 'utf8', timeout: 10_000 }) + assert.equal(result.error, undefined) + assert.equal(result.status, 1) + assert.ok(result.stderr.includes(diagnostic), result.stderr) + assert.ok(!result.stderr.includes('ERR_MODULE_NOT_FOUND'), result.stderr) + } + console.log('Desktop publisher pre-install entrypoints: OK') +} finally { + await rm(directory, { recursive: true, force: true }) +} diff --git a/apps/desktop-publisher/tests/workflow.spec.ts b/apps/desktop-publisher/tests/workflow.spec.ts index 738412c54a..0950cfec84 100644 --- a/apps/desktop-publisher/tests/workflow.spec.ts +++ b/apps/desktop-publisher/tests/workflow.spec.ts @@ -1,5 +1,5 @@ import { existsSync, readFileSync } from 'node:fs' -import { resolve, relative } from 'node:path' +import { join, resolve, relative } from 'node:path' import { load } from 'js-yaml' import { z } from 'zod' import { expect, it } from 'vitest' @@ -22,10 +22,35 @@ it('loads every rollout entry from its own installed package and the correct job for (const entry of job.steps) { if (!entry.run?.startsWith('node --import tsx ')) continue const directory = relative(checkoutRoot, resolve(root, entry['working-directory'] ?? '.')) - expect(directory).toBe('apps/desktop-publisher') + expect(directory).toBe(join('apps', 'desktop-publisher')) const script = entry.run.split(' ')[3]! expect(existsSync(resolve(root, directory, script))).toBe(true) } expect(job.steps.some(entry => entry.run?.includes('pnpm exec'))).toBe(false) } }) + +it.each(['desktop-rollout.yml', 'desktop-publish.yml'])('keeps %s preflights executable before install', (filename) => { + const workflow = workflowSchema.parse(load(readFileSync(resolve(root, '.github/workflows', filename), 'utf8'))) + let preflights = 0 + for (const job of Object.values(workflow.jobs)) { + const checkout = job.steps.find(entry => entry.uses?.startsWith('actions/checkout@')) + const checkoutRoot = resolve(root, checkout?.with?.path ?? '.') + for (const [index, entry] of job.steps.entries()) { + if (!entry.run?.startsWith('node apps/desktop-publisher/src/preflight-')) continue + preflights++ + const directory = relative(checkoutRoot, resolve(root, entry['working-directory'] ?? '.')) + expect(directory).toBe('') + expect(existsSync(resolve(root, entry.run.split(' ')[1]!))).toBe(true) + expect(index).toBeLessThan(job.steps.findIndex(candidate => candidate.run?.includes(' install '))) + } + } + expect(preflights).toBe(5) +}) + +it('separates rollout checkouts from full-workspace publication checkouts', () => { + const read = (filename: string) => workflowSchema.parse(load(readFileSync(resolve(root, '.github/workflows', filename), 'utf8'))) + const paths = (filename: string) => Object.values(read(filename).jobs).flatMap(job => job.steps.flatMap(entry => entry.uses?.startsWith('actions/checkout@') && entry.with?.path ? [entry.with.path] : [])) + const full = new Set(paths('desktop-publish.yml')) + for (const path of paths('desktop-rollout.yml')) expect(full.has(path)).toBe(false) +}) diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index dc6cb5f9e0..2216019fba 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -51,8 +51,8 @@ en: 617a89aeb28131b9 zh: 4d84bd5d86501c86 /deepseek-harness-desktop/package: - en: ac31ebdd9de54f34 - zh: 921e534d5c4b3a16 + en: 7200a35dbed997c3 + zh: 511d6961530757f1 /deepseek-harness-desktop/windows-installer-interface: en: f1302ed4a3ab58bb zh: cb53b9b349815028 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 68596d719f..e531d2c303 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -243,6 +243,7 @@ Use the dedicated guides for build and release operations. Shared Windows runner - [Desktop packaging](packaging/README.md): local and Actions builds, versions, deployment settings, artifacts, logs and verification. - [Windows signing and runner operations](windows-signing/README.md): machine setup, accepted isolation risks, signing credentials, token failures and cache maintenance. - [Desktop publication](publishing/README.md): upload credentials, release identity, fixed downloads, update feeds and upload recovery. +- [Publisher workspace](../desktop-publisher/README.md): dependency ownership and isolated rollout installation. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 13661f0590..239a59e34e 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -243,6 +243,7 @@ Desktop 在 Host 启动后、打开工作区前检查模型 API Key 引用是否 - [Desktop 打包](packaging/README.zh.md):本地与 Actions 构建、版本、部署配置、产物、日志和验收。 - [Windows 签名与 runner 运维](windows-signing/README.zh.md):机器部署、已接受的隔离风险、签名凭据、Token 失败与缓存维护。 - [Desktop 发布](publishing/README.zh.md):上传凭据、发布标识、固定下载、更新清单和上传恢复。 +- [发布工具 workspace](../desktop-publisher/README.zh.md):依赖归属与放量隔离安装。 diff --git a/apps/desktop/scripts/desktop-edgeone.ts b/apps/desktop/scripts/desktop-edgeone.ts index dedbd8ad1d..f1f1875f4a 100644 --- a/apps/desktop/scripts/desktop-edgeone.ts +++ b/apps/desktop/scripts/desktop-edgeone.ts @@ -1,10 +1,10 @@ /** Submit one production fixed-installer cache purge to EdgeOne. */ import type { teo } from 'tencentcloud-sdk-nodejs-teo' import type { DesktopPackageTargetName } from './package-target.ts' +import type { DesktopPurgeConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-purge-types.ts' import { desktopLatestInstallerFilename, requiredEnvironmentValue, resolveDesktopAutoUpdateEnvironment, resolveDesktopUploadConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { desktopTargetPlatform } from './desktop-build-paths.mjs' -import type { DesktopPurgeConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-purge-types.ts' export type { DesktopPurgeConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-purge-types.ts' /** The single SDK operation needed to submit a purge. */ diff --git a/apps/desktop/scripts/desktop-upload-plan.ts b/apps/desktop/scripts/desktop-upload-plan.ts index 9c8d9c47e7..2e57bdb4c2 100644 --- a/apps/desktop/scripts/desktop-upload-plan.ts +++ b/apps/desktop/scripts/desktop-upload-plan.ts @@ -1,11 +1,12 @@ /** Validate packaged Desktop update artifacts before any network upload begins. */ +import type { DesktopPackageTargetName } from './package-target.ts' +import type { DesktopUploadArtifact, DesktopUploadPlan } from '@deepseek-ai/dsh-desktop-publisher/desktop-upload-types.ts' import { createHash } from 'node:crypto' import { createReadStream } from 'node:fs' import { readFile, stat } from 'node:fs/promises' import { basename, join, resolve } from 'node:path' import { dump, load } from 'js-yaml' -import type { DesktopPackageTargetName } from './package-target.ts' import { desktopBuildRecordFilename, desktopLatestInstallerFilename, @@ -15,6 +16,8 @@ import { import { desktopTargetBuildPaths } from './desktop-build-paths.mjs' import { validateDesktopBuildVersion } from './desktop-build-version.mjs' +export type { DesktopUploadArtifact, DesktopUploadPlan } from '@deepseek-ai/dsh-desktop-publisher/desktop-upload-types.ts' + const APP_ROOT = resolve(import.meta.dirname, '..') const REPOSITORY_ROOT = resolve(APP_ROOT, '..', '..') const TARGETS = { @@ -27,9 +30,6 @@ const TARGETS = { readonly os: string }> -import type { DesktopUploadArtifact, DesktopUploadPlan } from '@deepseek-ai/dsh-desktop-publisher/desktop-upload-types.ts' -export type { DesktopUploadArtifact, DesktopUploadPlan } from '@deepseek-ai/dsh-desktop-publisher/desktop-upload-types.ts' - /** Filesystem and environment inputs used to validate one upload. */ export interface DesktopUploadPlanOptions { /** Publish only the installer at its fixed download URL, replacing the previous object. */ diff --git a/apps/desktop/scripts/desktop-upload-run.ts b/apps/desktop/scripts/desktop-upload-run.ts index ccf528b1f6..584892e684 100644 --- a/apps/desktop/scripts/desktop-upload-run.ts +++ b/apps/desktop/scripts/desktop-upload-run.ts @@ -13,7 +13,12 @@ const FAILURE_CODES = new Set(['AccessDenied', 'InternalError', 'NoSuchBucket', 'RequestTimeout', 'TimeoutError', 'AbortError', 'ECONNRESET', 'ETIMEDOUT', 'ENOTFOUND', 'ENOSPC', 'EACCES', 'EPERM', 'ENOENT']) /** Object keys fingerprinted into every upload record to bind evidence to this uploader. */ -const UPLOADER_SOURCES = ['desktop-upload-run.ts', 'upload-target.ts', 'desktop-upload-plan.ts', 'desktop-cos.ts'] +const UPLOADER_SOURCES = { + 'desktop-upload-run.ts': new URL('./desktop-upload-run.ts', import.meta.url), + 'upload-target.ts': new URL('./upload-target.ts', import.meta.url), + 'desktop-upload-plan.ts': new URL('./desktop-upload-plan.ts', import.meta.url), + 'desktop-cos.ts': new URL(import.meta.resolve('@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts')), +} async function fingerprint(artifact: DesktopUploadArtifact) { const sha512 = createHash('sha512') @@ -83,10 +88,8 @@ export async function uploadDesktopRelease(plan: DesktopUploadPlan, cos: COS, re artifacts.push({ ...artifact, ...await fingerprint(artifact) }) } const sourceSha256: Record = {} - for (const filename of UPLOADER_SOURCES) { - sourceSha256[filename] = createHash('sha256').update(await readFile(filename === 'desktop-cos.ts' - ? new URL(import.meta.resolve('@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts')) - : join(import.meta.dirname, filename))).digest('hex') + for (const [filename, source] of Object.entries(UPLOADER_SOURCES)) { + sourceSha256[filename] = createHash('sha256').update(await readFile(source)).digest('hex') } await writeFile(join(directory, 'plan.json'), `${JSON.stringify({ schemaVersion: 1, environment: plan.environment, target: plan.target, version: plan.version, bucket: plan.bucket, diff --git a/apps/desktop/scripts/retain-desktop-ci.ts b/apps/desktop/scripts/retain-desktop-ci.ts index fb53e9c065..d26e6a068c 100644 --- a/apps/desktop/scripts/retain-desktop-ci.ts +++ b/apps/desktop/scripts/retain-desktop-ci.ts @@ -1,9 +1,8 @@ -import { desktopReleasesRoot } from '@deepseek-ai/dsh-desktop-publisher/desktop-releases-root.ts' -export { desktopReleasesRoot } from '@deepseek-ai/dsh-desktop-publisher/desktop-releases-root.ts' /** Retain completed CI packages for later manual publication. */ import { appendFile, readFile } from 'node:fs/promises' import { join, resolve } from 'node:path' import { desktopTargetBuildPaths, resolveDesktopBuildTarget } from './desktop-build-paths.mjs' +import { desktopReleasesRoot } from '@deepseek-ai/dsh-desktop-publisher/desktop-releases-root.ts' import { desktopBuildRecordFilename, desktopUpdateMetadataFilename, resolveDesktopUpdateChannel } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { loadDesktopPackageEnvironment } from './desktop-package-environment.mjs' import { retainDesktopRelease, type DesktopRetainedSource } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' @@ -11,13 +10,14 @@ import { validateDesktopBuildVersion } from './desktop-build-version.mjs' import { desktopPublishRunnersSchema } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-targets.ts' import { desktopPublishQualificationError } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-qualification.mjs' +export { desktopReleasesRoot } from '@deepseek-ai/dsh-desktop-publisher/desktop-releases-root.ts' + function required(env: NodeJS.ProcessEnv, name: string): string { const value = env[name] if (!value) throw new Error(`desktop retention: ${name} is required`) return value } - /** * Resolve the original machine's unique label before expensive packaging work. * @param env Machine identity, target and administrator-owned runner mapping. diff --git a/apps/desktop/tests/desktop-publish-local-preflight.spec.ts b/apps/desktop/tests/desktop-publish-local-preflight.spec.ts index 9f5dccd580..56aa918b92 100644 --- a/apps/desktop/tests/desktop-publish-local-preflight.spec.ts +++ b/apps/desktop/tests/desktop-publish-local-preflight.spec.ts @@ -2,7 +2,7 @@ import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, it } from 'vitest' -import { preflightDesktopPublishLocal } from '../scripts/preflight-desktop-publish-local.mjs' +import { preflightDesktopPublishLocal } from '@deepseek-ai/dsh-desktop-publisher/preflight-desktop-publish-local.mjs' it('checks the retained preset before approval and the approved preset before upload without opening credentials', async () => { const root = await mkdtemp(join(tmpdir(), 'publish-preflight-')) @@ -39,8 +39,8 @@ it('runs the local preflight before dependency installation in both self-hosted const workflow = await readFile('.github/workflows/desktop-publish.yml', 'utf8') for (const job of ['prepare', 'publish']) { const section = workflow.split(`\n ${job}:`)[1]!.split(/\n \w+:/u)[0]! - expect(section.indexOf('node apps/desktop/scripts/preflight-desktop-publish-local.mjs')).toBeGreaterThan(0) - expect(section.indexOf('node apps/desktop/scripts/preflight-desktop-publish-local.mjs')).toBeLessThan(section.indexOf('pnpm install --frozen-lockfile')) + expect(section.indexOf('node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs')).toBeGreaterThan(0) + expect(section.indexOf('node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs')).toBeLessThan(section.indexOf('pnpm install --frozen-lockfile')) } }) diff --git a/apps/desktop/tests/desktop-publish-preflight.spec.ts b/apps/desktop/tests/desktop-publish-preflight.spec.ts index 755a0ce8a6..0398d58b81 100644 --- a/apps/desktop/tests/desktop-publish-preflight.spec.ts +++ b/apps/desktop/tests/desktop-publish-preflight.spec.ts @@ -1,5 +1,5 @@ import { expect, it } from 'vitest' -import { preflightDesktopPublish } from '../scripts/preflight-desktop-publish.mjs' +import { preflightDesktopPublish } from '@deepseek-ai/dsh-desktop-publisher/preflight-desktop-publish.mjs' it.each([ ['macos-x64-unnotarized-debug-1.0.0-42-2', '跳过了公证'], diff --git a/apps/desktop/tests/desktop-rollout.spec.ts b/apps/desktop/tests/desktop-rollout.spec.ts index 4637982916..c7457ea7bc 100644 --- a/apps/desktop/tests/desktop-rollout.spec.ts +++ b/apps/desktop/tests/desktop-rollout.spec.ts @@ -82,7 +82,7 @@ it.each([ expect(await rolloutDesktopRelease(f.plan, 100, operations)).toEqual({ before: 100, after: 100 }) expect(await rolloutDesktopRelease(f.plan, undefined, operations)).toEqual({ before: 100, after: 100 }) expect(mock.writes).toHaveLength(2) - expect(new Set(mock.reads)).toEqual(new Set([f.plan.upload.artifacts[0]!.key])) + expect(new Set(mock.reads)).toEqual(new Set([f.plan.upload.artifacts[0].key])) for (const [index, value] of mock.writes.entries()) { expect(load(value)).toEqual({ ...original, stagingPercentage: index === 0 ? 30 : 100 }) } diff --git a/apps/desktop/tests/desktop-upload-run.spec.ts b/apps/desktop/tests/desktop-upload-run.spec.ts index d3e26bf25b..775bc8e9b8 100644 --- a/apps/desktop/tests/desktop-upload-run.spec.ts +++ b/apps/desktop/tests/desktop-upload-run.spec.ts @@ -7,6 +7,7 @@ import { afterEach, describe, expect, it } from 'vitest' import { createDesktopCos, DESKTOP_COS_REGION } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import { uploadDesktopRelease } from '../scripts/desktop-upload-run.ts' import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' +// Repository-only fixture: deliberately excluded from the publisher runtime exports. import { answer, cosError, startCosLoopback, type CosLoopback, type CosLoopbackRequest } from '../../desktop-publisher/tests/cos-loopback.ts' const roots: string[] = [] diff --git a/apps/desktop/tests/installed-update-cos.spec.ts b/apps/desktop/tests/installed-update-cos.spec.ts index 81f9006c4f..f84c77c7a3 100644 --- a/apps/desktop/tests/installed-update-cos.spec.ts +++ b/apps/desktop/tests/installed-update-cos.spec.ts @@ -5,6 +5,7 @@ import { join } from 'node:path' import type COS from 'cos-nodejs-sdk-v5' import { afterEach, describe, expect, it, vi } from 'vitest' import { createInstalledUpdateCos } from '../scripts/installed-update-cos.ts' +// Repository-only fixture: deliberately excluded from the publisher runtime exports. import { answer, cosError, startCosLoopback, type CosLoopback, type CosLoopbackResponder } from '../../desktop-publisher/tests/cos-loopback.ts' const state = vi.hoisted(() => ({ diff --git a/apps/desktop/tests/purge-command.spec.ts b/apps/desktop/tests/purge-command.spec.ts index 9b826b0830..8bfcb69a3a 100644 --- a/apps/desktop/tests/purge-command.spec.ts +++ b/apps/desktop/tests/purge-command.spec.ts @@ -31,7 +31,11 @@ it('forwards the documented pnpm purge command through both package scripts to t await symlink(join(root, 'node_modules', dependency), join(directory, 'node_modules', dependency), 'junction') } await mkdir(join(directory, 'node_modules/@deepseek-ai'), { recursive: true }) - await symlink(join(root, 'apps/desktop-publisher'), join(directory, 'node_modules/@deepseek-ai/dsh-desktop-publisher'), 'junction') + const publisher = join(directory, 'node_modules/@deepseek-ai/dsh-desktop-publisher') + await mkdir(publisher) + await writeFile(join(publisher, 'package.json'), JSON.stringify({ type: 'module', exports: { './*': './*' } })) + await copyFile(join(root, 'apps/desktop-publisher/src/desktop-auto-update-environment.mjs'), join(publisher, 'desktop-auto-update-environment.mjs')) + await writeFile(join(publisher, 'desktop-cos.ts'), "export const createDesktopCos = () => { throw new Error('unexpected COS') }") await copyFile(join(root, 'apps/desktop/scripts/upload-target.ts'), join(scripts, 'upload-target.ts')) for (const filename of ['desktop-build-paths.mjs']) { await copyFile(join(root, 'apps/desktop/scripts', filename), join(scripts, filename)) @@ -39,7 +43,6 @@ it('forwards the documented pnpm purge command through both package scripts to t // Only command forwarding and parsing are under test; all external work fails closed. const stubs = { 'desktop-package-environment.mjs': "export const loadDesktopPackageEnvironment = () => ({ DSH_DESKTOP_AUTO_UPDATE_ENV: 'production' })", - 'desktop-cos.ts': "export const createDesktopCos = () => { throw new Error('unexpected COS') }", 'desktop-upload-plan.ts': "export const createDesktopUploadPlan = () => { throw new Error('unexpected installer read') }", 'desktop-upload-run.ts': "export const uploadDesktopRelease = () => { throw new Error('unexpected upload') }", 'desktop-release-tag.ts': "export const desktopReleaseTag = () => { throw new Error('unexpected tag') }; export const tagDesktopRelease = desktopReleaseTag", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8057f54080..e8468e91e3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -734,9 +734,6 @@ importers: specifier: ^8.21.3 version: 8.21.3 devDependencies: - '@deepseek-ai/dsh-desktop-publisher': - specifier: workspace:* - version: link:../desktop-publisher '@deepseek-ai/dsh-app-boot': specifier: workspace:* version: link:../../packages/boot/app-boot @@ -767,6 +764,9 @@ importers: '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* version: link:../../packages/credentials/deepseek-account + '@deepseek-ai/dsh-desktop-publisher': + specifier: workspace:* + version: link:../desktop-publisher '@deepseek-ai/dsh-home-paths': specifier: workspace:* version: link:../../packages/util/home-paths @@ -846,27 +846,6 @@ importers: specifier: 4.6.6 version: 4.6.6 - apps/desktop-publisher: - dependencies: - zod: - specifier: 4.6.6 - version: 4.6.6 - js-yaml: - specifier: ^4.3.2 - version: 4.3.2 - semver: - specifier: ^7.8.5 - version: 7.8.5 - cos-nodejs-sdk-v5: - specifier: 3.0.0 - version: 3.0.0 - tencentcloud-sdk-nodejs-teo: - specifier: 4.1.330 - version: 4.1.330(supports-color@9.4.0) - tsx: - specifier: ^4.23.13 - version: 4.23.13 - apps/desktop-host: dependencies: '@deepseek-ai/cordis': @@ -928,6 +907,27 @@ importers: specifier: workspace:* version: link:../../packages/util/workspace-path + apps/desktop-publisher: + dependencies: + cos-nodejs-sdk-v5: + specifier: 3.0.0 + version: 3.0.0 + js-yaml: + specifier: ^4.3.2 + version: 4.3.2 + semver: + specifier: ^7.8.5 + version: 7.8.5 + tencentcloud-sdk-nodejs-teo: + specifier: 4.1.330 + version: 4.1.330(supports-color@9.4.0) + tsx: + specifier: ^4.23.13 + version: 4.23.13 + zod: + specifier: 4.6.6 + version: 4.6.6 + apps/plugin-market-generator: dependencies: '@deepseek-ai/dsh-plugin-market-index': diff --git a/scripts/desktop-publish-workflow.spec.ts b/scripts/desktop-publish-workflow.spec.ts index 26df0d6b73..e6093fe599 100644 --- a/scripts/desktop-publish-workflow.spec.ts +++ b/scripts/desktop-publish-workflow.spec.ts @@ -24,7 +24,7 @@ it('rejects debugging packages before dependency setup and pins the checked atte const preflight = steps.findIndex(step => step.id === 'preflight') expect(preflight).toBeGreaterThan(0) expect(preflight).toBeLessThan(steps.findIndex(step => step.uses?.startsWith('pnpm/'))) - expect(steps[preflight]?.run).toBe('node apps/desktop/scripts/preflight-desktop-publish.mjs') + expect(steps[preflight]?.run).toBe('node apps/desktop-publisher/src/preflight-desktop-publish.mjs') expect(steps.find(step => step.id === 'route')?.env?.DESKTOP_PACKAGE_ATTEMPT).toBe('${{ steps.preflight.outputs.attempt }}') }) @@ -92,7 +92,7 @@ it('defaults to production website upload and separates cache-only recovery', () for (const job of [upload, purge]) { expect(job.if).toBe("inputs.upload_website && needs.prepare.outputs.preset != 'test'") expect(job.environment).toBe('desktop-production') - const preflight = job.steps.findIndex(step => step.run === 'node apps/desktop/scripts/preflight-desktop-publish-local.mjs') + const preflight = job.steps.findIndex(step => step.run === 'node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs') expect(preflight).toBeGreaterThan(-1) expect(preflight).toBeLessThan(job.steps.findIndex(step => step.run === 'pnpm install --frozen-lockfile')) expect(job.env?.DESKTOP_WEBSITE_APPROVAL).toBe('${{ needs.prepare.outputs.website-approval }}') From fe91df778bbdfe3453b24c5f2b6c75af0c6ff3c6 Mon Sep 17 00:00:00 2001 From: winewill Date: Thu, 5 Nov 2026 17:49:30 +0800 Subject: [PATCH 009/450] test(ci): preserve worker limits with required publisher smoke --- .github/workflows/ci-windows.yml | 3 ++- .github/workflows/ci.yml | 4 +++- scripts/ci-workflow.spec.ts | 19 ++++++++++++------- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci-windows.yml b/.github/workflows/ci-windows.yml index 142f4dfbd9..c3ea5c58fc 100644 --- a/.github/workflows/ci-windows.yml +++ b/.github/workflows/ci-windows.yml @@ -48,7 +48,7 @@ jobs: - uses: pnpm/action-setup@v5.0.0 with: package_json_file: publisher-isolated/package.json - dest: ${{ runner.temp }}/setup-pnpm-publisher-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} + dest: ${{ runner.temp }}/setup-pnpm-js-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} - name: Install only publisher production dependencies working-directory: publisher-isolated run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts @@ -63,6 +63,7 @@ jobs: # Blacksmith uses 2 vCPU for file-serial native tests and 16 for coverage # and the shared build/observational workspace. windows-build: + needs: windows-publisher if: github.event_name == 'pull_request' runs-on: >- ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-16vcpu-windows-2025' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d74e2355e0..fc83d5c7f9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,6 +21,7 @@ concurrency: jobs: publisher-isolated: strategy: + max-parallel: 1 fail-fast: false matrix: os: [linux, macos] @@ -46,7 +47,7 @@ jobs: - uses: pnpm/action-setup@v5.0.0 with: package_json_file: publisher-isolated/package.json - dest: ${{ runner.temp }}/setup-pnpm-publisher-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} - name: Install only publisher production dependencies working-directory: publisher-isolated run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts @@ -494,6 +495,7 @@ jobs: node-compat: + needs: publisher-isolated if: github.event_name == 'pull_request' # Under the selfhosted leg this job admits only repository-owned PR code # to the persistent shared VM; the blacksmith branch targets ephemeral diff --git a/scripts/ci-workflow.spec.ts b/scripts/ci-workflow.spec.ts index ed7a360894..56bb3f9303 100644 --- a/scripts/ci-workflow.spec.ts +++ b/scripts/ci-workflow.spec.ts @@ -41,12 +41,17 @@ describe('CI workflow', () => { }) expect(workflowJob(ci, 'all-checks-passed').needs).toContain('node-compat') const ordinaryJobs = Object.entries(ci.jobs) - .filter(([name]) => !['node-compat', 'all-checks-passed'].includes(name)) + .filter(([name]) => !['node-compat', 'all-checks-passed', 'publisher-isolated'].includes(name)) for (const [name, job] of ordinaryJobs) { if (!isRecord(job)) throw new TypeError(`${name} must define a job`) expect(job).not.toHaveProperty('strategy') expect(job).not.toHaveProperty('uses') } + // Publisher smoke reuses the compatibility/build concurrency slots before those jobs start. + expect(compatibility.needs).toBe('publisher-isolated') + expect(workflowJob(ci, 'publisher-isolated').strategy).toMatchObject({ 'max-parallel': 1, matrix: { os: ['linux', 'macos'] } }) + expect(workflowJob(ciWindows, 'windows-build').needs).toBe('windows-publisher') + expect(workflowJob(ciWindows, 'windows-publisher').defaults).toEqual({ run: { shell: 'pwsh' } }) // Python reports its own required verdict, so neither its jobs nor a // reusable workflow caller remain in the Linux or Windows workflow. expect(Object.keys(ci.jobs).filter(name => name.startsWith('python'))).toEqual([]) @@ -60,7 +65,7 @@ describe('CI workflow', () => { expect(runtime.with).toMatchObject({ targets: 'node24-linux-x64,node24-win-x64' }) expect(runtime.uses).toBe('./.github/workflows/build-exe-for-python-sdk.yml') const windowsJobs = Object.entries(ciWindows.jobs) - .filter(([name]) => name !== 'windows-checks-passed') + .filter(([name]) => !['windows-checks-passed', 'windows-publisher'].includes(name)) for (const [name, job] of windowsJobs) { if (!isRecord(job)) throw new TypeError(`${name} must define a job`) expect(job).not.toHaveProperty('strategy') @@ -95,7 +100,7 @@ describe('CI workflow', () => { expect(afterSdk).toBeLessThanOrEqual(11) }) - it('keeps the union of required PR verdicts equal to the pre-split blocking set', () => { + it('keeps required PR verdicts covering runtime and publisher jobs', () => { const verdicts = [ ['ci.yml', 'all-checks-passed'], ['ci-windows.yml', 'windows-checks-passed'], @@ -112,9 +117,7 @@ describe('CI workflow', () => { expect(verdict.needs.every(id => typeof id === 'string' && id in jobs)).toBe(true) blocking.push(...(verdict.needs as string[])) } - // Splitting the workflows only moves jobs between verdicts; the blocking - // set itself must stay identical, or branch protection would accept a - // failure it rejected before the split. + // Every blocking lane must contribute to a branch-protection verdict. expect(blocking.sort()).toEqual([ 'node-24', 'node-24-bench', @@ -122,10 +125,12 @@ describe('CI workflow', () => { 'node-24-coverage', 'node-24-lint', 'node-compat', + 'publisher-isolated', 'python-runtime', 'python-sdk', 'windows-build', 'windows-native-tests', + 'windows-publisher', ]) }) @@ -547,7 +552,7 @@ describe('CI workflow', () => { expect(aggregate.needs).not.toContain('windows') // windows-coverage is temporarily non-blocking while Windows ACP // half-close tests are stabilized; observational stays out too. - expect(windowsAggregate.needs).toEqual(['windows-build', 'windows-native-tests']) + expect(windowsAggregate.needs).toEqual(['windows-publisher', 'windows-build', 'windows-native-tests']) expect(windowsAggregate.name).toBe('windows checks passed') expect(windowsAggregate['runs-on']).toBe(aggregate['runs-on']) expect(windowsAggregate.if).toBe(aggregate.if) From eea6dfef87de9dfce21359b847d49d9cfa6f15f2 Mon Sep 17 00:00:00 2001 From: winewill Date: Thu, 5 Nov 2026 17:55:24 +0800 Subject: [PATCH 010/450] test(snapshots): refresh terminal runtime context reminder --- snapshots/session/terminal-panel-tools/session.v4.jsonl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snapshots/session/terminal-panel-tools/session.v4.jsonl b/snapshots/session/terminal-panel-tools/session.v4.jsonl index 01574413c3..290e17f9f6 100644 --- a/snapshots/session/terminal-panel-tools/session.v4.jsonl +++ b/snapshots/session/terminal-panel-tools/session.v4.jsonl @@ -8,7 +8,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"My tests fail in my terminal. What does it say?"}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-pro"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-pro"}} {"type":"session/title","data":{"title":"My tests fail in my","messageSeqs":[8],"source":{"kind":"fallback"}}} From 261f4704113baea0cd5817ea538413ed3a3e7473 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Thu, 5 Nov 2026 19:25:15 +0800 Subject: [PATCH 011/450] feat(web): move background jobs and subagents into the Session panel --- .../ui-agent-team/src/client/TeamBoard.tsx | 2 +- .../client/ui-agent-team/src/client/mount.ts | 4 +- .../tests/browser-plugin.client.spec.ts | 6 +- packages/client/ui-jobs/package.json | 8 +- ...tion.module.css => JobsSection.module.css} | 172 +- .../{JobListAction.tsx => JobsSection.tsx} | 276 +-- packages/client/ui-jobs/src/client/index.ts | 33 +- packages/client/ui-jobs/src/client/locales.ts | 24 - .../tests/browser-plugin.client.spec.ts | 28 +- .../tests/job-list-action.client.spec.tsx | 950 --------- .../tests/jobs-section.client.spec.tsx | 465 +++++ packages/client/ui-jobs/tsconfig.json | 12 +- packages/client/ui-subagent/package.json | 26 +- ....module.css => SubagentCatalog.module.css} | 120 +- .../src/client/SubagentCatalog.tsx | 559 ++++++ .../src/client/SubagentHeaderLineage.tsx | 919 ++------- .../src/client/SubagentsSection.tsx | 94 + .../client/ui-subagent/src/client/index.ts | 46 +- .../client/ui-subagent/src/client/locales.ts | 32 - .../client/ui-subagent/src/client/slots.ts | 7 +- .../tests/browser-plugin.client.spec.ts | 35 +- .../tests/conversation-ui.client.spec.tsx | 1725 ++++++----------- packages/client/ui-subagent/tsconfig.json | 33 +- pnpm-lock.yaml | 9 +- 24 files changed, 2081 insertions(+), 3504 deletions(-) rename packages/client/ui-jobs/src/client/{JobListAction.module.css => JobsSection.module.css} (67%) rename packages/client/ui-jobs/src/client/{JobListAction.tsx => JobsSection.tsx} (60%) delete mode 100644 packages/client/ui-jobs/tests/job-list-action.client.spec.tsx create mode 100644 packages/client/ui-jobs/tests/jobs-section.client.spec.tsx rename packages/client/ui-subagent/src/client/{SubagentHeaderLineage.module.css => SubagentCatalog.module.css} (81%) create mode 100644 packages/client/ui-subagent/src/client/SubagentCatalog.tsx create mode 100644 packages/client/ui-subagent/src/client/SubagentsSection.tsx diff --git a/packages/client/ui-agent-team/src/client/TeamBoard.tsx b/packages/client/ui-agent-team/src/client/TeamBoard.tsx index d6d0538fa9..42d687d854 100644 --- a/packages/client/ui-agent-team/src/client/TeamBoard.tsx +++ b/packages/client/ui-agent-team/src/client/TeamBoard.tsx @@ -14,7 +14,7 @@ import css from './TeamBoard.module.css' /** Full props of the task board below the shared subagent catalog. */ export type TeamBoardProps = - PropsRuntime<'conversation.session.header.actions.subagent.footer'> & PropsLocale + PropsRuntime<'conversation.session.panel.subagents.footer'> & PropsLocale type VisibleTask = TeamTaskView & { status: Exclude } diff --git a/packages/client/ui-agent-team/src/client/mount.ts b/packages/client/ui-agent-team/src/client/mount.ts index 833267e39e..6a899617ec 100644 --- a/packages/client/ui-agent-team/src/client/mount.ts +++ b/packages/client/ui-agent-team/src/client/mount.ts @@ -65,7 +65,7 @@ export function registerAgentTeamUi(ctx: ClientContext): void { }, TeamModeToggle)) }) }) - ctx.slots.inject('conversation.session.header.actions.subagent.footer', () => ctx.slots.register({ - name: 'conversation.session.header.actions.subagent.footer', id: 'agent-team', locale: NS, + ctx.slots.inject('conversation.session.panel.subagents.footer', () => ctx.slots.register({ + name: 'conversation.session.panel.subagents.footer', id: 'agent-team', locale: NS, }, TeamBoard)) } diff --git a/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts b/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts index ba964a033f..688ef0ebcc 100644 --- a/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts @@ -19,14 +19,14 @@ async function bench() { const collapseHeader = ctx.slots.register({ name: 'root', children: { - 'conversation.session.header.actions.subagent.footer': { kind: 'list', scope: 'session' }, + 'conversation.session.panel.subagents.footer': { kind: 'list', scope: 'session' }, 'conversation.input.model': { kind: 'single', scope: 'session' }, 'shell.overlay': { kind: 'list', scope: 'root' }, }, } as never, () => null) const fiber = ctx.plugin({ inject: [...inject], apply }) await fiber.await() - const entry = () => ctx.slots.entries('conversation.session.header.actions.subagent.footer') + const entry = () => ctx.slots.entries('conversation.session.panel.subagents.footer') .find(candidate => candidate.component === TeamBoard) return { ctx, fiber, entry, collapseHeader } } @@ -55,7 +55,7 @@ describe('task-board browser plugin', () => { expect(b.entry()).toBeUndefined() b.ctx.slots.register({ name: 'root', - children: { 'conversation.session.header.actions.subagent.footer': { kind: 'list', scope: 'session' } }, + children: { 'conversation.session.panel.subagents.footer': { kind: 'list', scope: 'session' } }, } as never, () => null) await Promise.resolve() expect(b.entry()).toBeDefined() diff --git a/packages/client/ui-jobs/package.json b/packages/client/ui-jobs/package.json index 2c8943e4c7..3c50087660 100644 --- a/packages/client/ui-jobs/package.json +++ b/packages/client/ui-jobs/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-client-ui-jobs", - "description": "Session-header background-job list with on-demand streaming record panels", + "description": "Session panel background-job list with on-demand streaming record panels", "version": "0.2.2-rc.1", "type": "module", "main": "lib/index.js", @@ -39,10 +39,10 @@ "@deepseek-ai/dsh-api-job-controller": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", - "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-session": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-panel": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-jobs": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", @@ -63,8 +63,8 @@ "inject": [ "@deepseek-ai/dsh-api-job-controller", "@deepseek-ai/dsh-client-locale", - "@deepseek-ai/dsh-client-ui-conversation", - "@deepseek-ai/dsh-client-ui-primitives" + "@deepseek-ai/dsh-client-ui-primitives", + "@deepseek-ai/dsh-client-ui-session-panel" ], "platform": "web" } diff --git a/packages/client/ui-jobs/src/client/JobListAction.module.css b/packages/client/ui-jobs/src/client/JobsSection.module.css similarity index 67% rename from packages/client/ui-jobs/src/client/JobListAction.module.css rename to packages/client/ui-jobs/src/client/JobsSection.module.css index 6b72ce3241..333bb482f1 100644 --- a/packages/client/ui-jobs/src/client/JobListAction.module.css +++ b/packages/client/ui-jobs/src/client/JobsSection.module.css @@ -1,121 +1,10 @@ -.trigger { - display: inline-flex; - align-items: center; - gap: 4px; - min-height: 28px; - padding: 3px 2px; - border: 0; - border-radius: var(--dsw-radius-sm); - background: transparent; - color: var(--dsw-alias-label-tertiary); - font-size: 12px; - line-height: 18px; - cursor: pointer; -} - -.trigger:focus-visible { - color: var(--dsw-alias-label-secondary); -} - -@media (hover: hover) { - .trigger:hover { - color: var(--dsw-alias-label-secondary); - } -} - -.activitySlot { - display: inline-flex; - flex: none; - align-items: center; - justify-content: center; - width: 14px; - height: 14px; -} - -.trigger .compactIcon { - display: none; -} - -@container (max-width: 460px) { - .trigger .compactIcon { - display: block; - } - - .trigger .textModeActivity { - display: none; - } - - .trigger .count { - display: none; - } - - .trigger { - box-sizing: border-box; - width: 28px; - height: 28px; - padding: 0; - justify-content: center; - color: var(--dsw-alias-label-secondary); - } - - .trigger .activitySlot, - .trigger .activitySlot > svg { - width: 15px; - height: 15px; - } - - .trigger:focus-visible { - color: var(--dsw-alias-label-secondary); - } - - .trigger:active { - background: var(--dsw-alias-interactive-bg-active); - } - - @media (hover: hover) { - .trigger:hover { - color: var(--dsw-alias-label-secondary); - background: var(--dsw-alias-interactive-bg-hover); - } - } -} - -/* Portaled above the right sidebar (at most 40) and below modal overlays (1000). */ -.menu { - position: fixed; - z-index: 100; - box-sizing: border-box; - display: flex; - flex-direction: column; - width: 500px; - max-width: min(560px, calc(100vw - 32px)); - max-height: min(480px, calc(100dvh - 140px)); - overflow: hidden; - --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2); - --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2); - --dsw-elevation-stroke-color: var(--dsw-alias-border-l1); - box-shadow: var(--dsw-elevation-prominent); - position-area: none; - top: max(12px, calc(anchor(bottom) + 5px)); - bottom: 12px; - left: max(12px, anchor(left)); - right: 12px; - position-try-fallbacks: --dsh-jobs-window, --dsh-jobs-opposite, --dsh-jobs-wide-opposite, --dsh-jobs-tall, --dsh-jobs-viewport; - align-self: start; - justify-self: start; - height: fit-content; - min-height: 0; - margin: 0; -} - -.menuBody { +/* Rows sit inside the Session panel section body, which supplies the inset and scrolling. */ +.list { display: flex; flex-direction: column; gap: 1px; - min-height: 0; margin: 0; - padding: 4px; - overflow: auto; + padding: 0; list-style: none; } @@ -205,9 +94,9 @@ } } -/* The kind badge shares the card fill, so it pops on the menu surface instead. */ +/* The kind badge shares the card fill, so it pops on the panel surface instead. */ .rowLineLive .kind { - background: var(--dsw-specific-menu); + background: var(--dsw-alias-bg-layer-1); } .rowLine .row { @@ -243,7 +132,7 @@ height: 20px; border: 0.5px solid var(--dsw-alias-border-l2); border-radius: var(--dsw-radius-sm); - background: var(--dsw-specific-menu); + background: var(--dsw-alias-bg-layer-1); } /* Two-press kill affordance on running job rows: same persistent square. */ @@ -258,7 +147,7 @@ padding: 0; border: 0.5px solid var(--dsw-alias-border-l2); border-radius: var(--dsw-radius-sm); - background: var(--dsw-specific-menu); + background: var(--dsw-alias-bg-layer-1); color: var(--dsw-alias-label-secondary); cursor: pointer; } @@ -398,7 +287,7 @@ } /* A failed task's detail is the producer's raw text, so it has no bound; - without this it widens the row past the menu instead of eliding like .label. */ + without this it widens the row past the panel instead of eliding like .label. */ .status { flex: none; max-width: 60%; @@ -455,48 +344,3 @@ .noticeError { color: var(--dsw-alias-state-error-primary); } - -@position-try --dsh-jobs-window { - position-area: none; - top: max(12px, calc(anchor(bottom) + 5px)); - bottom: 12px; - left: 12px; - right: 12px; - margin: 0; - align-self: safe start; - justify-self: safe end; -} - -@position-try --dsh-jobs-opposite { - top: max(12px, var(--dsh-frame-overlay-top, 12px)); - bottom: max(12px, calc(anchor(top) + 5px)); - align-self: end; -} - -@position-try --dsh-jobs-wide-opposite { - top: max(12px, var(--dsh-frame-overlay-top, 12px)); - bottom: max(12px, calc(anchor(top) + 5px)); - left: 12px; - right: 12px; - align-self: end; - justify-self: safe end; -} - -@position-try --dsh-jobs-tall { - position-area: none; - top: max(12px, var(--dsh-frame-overlay-top, 12px)); - bottom: 12px; - left: max(12px, anchor(left)); - right: 12px; - margin: 0; - align-self: safe start; - justify-self: start; -} - -@position-try --dsh-jobs-viewport { - position-area: none; - inset: max(12px, var(--dsh-frame-overlay-top, 12px)) 12px 12px; - margin: 0; - align-self: safe start; - justify-self: safe end; -} diff --git a/packages/client/ui-jobs/src/client/JobListAction.tsx b/packages/client/ui-jobs/src/client/JobsSection.tsx similarity index 60% rename from packages/client/ui-jobs/src/client/JobListAction.tsx rename to packages/client/ui-jobs/src/client/JobsSection.tsx index 1c88d77ef9..b348e89777 100644 --- a/packages/client/ui-jobs/src/client/JobListAction.tsx +++ b/packages/client/ui-jobs/src/client/JobsSection.tsx @@ -1,19 +1,17 @@ -import { useCallback, useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type PointerEvent } from 'react' -import { createPortal } from 'react-dom' +import { useEffect, useMemo, useState } from 'react' import type { JobsSnapshot, JobView, ObservedJob } from '@deepseek-ai/dsh-api-job-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { - IconChevronDownOutlineRegular, IconLayersOutlineRegular, IconStopFillRegular, MenuSurface, StateDot, TerminalBlock, Tooltip, - useDismissOnOutsidePointer, + IconChevronDownOutlineRegular, IconStopFillRegular, StateDot, TerminalBlock, type StateDotState, type TerminalBlockLabels, } from '@deepseek-ai/dsh-client-ui-primitives' import type { InjectFace, PropsLocale, PropsRuntime, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' import { NS } from './locales.ts' -import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' -import css from './JobListAction.module.css' +import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client' +import css from './JobsSection.module.css' -/** Registration-side business face for the job list. */ -export interface JobListInjected { +/** Registration-side business face for the background-jobs section. */ +export interface JobsSectionInjected { hooks: { /** Client jobs snapshot (rosters and observations) bound by the renderer as useJobs. */ jobs: { @@ -39,18 +37,15 @@ export interface JobListInjected { killJob: (sessionId: SessionId, jobId: string) => Promise } -/** Full props for the session-header job-list action. */ -export type JobListActionProps = - PropsRuntime<'conversation.session.header.actions'> +/** Full props for the Session panel's background-jobs section. */ +export type JobsSectionProps = + PropsRuntime<'conversation.session.panel.section'> & PropsLocale - & InjectFace + & InjectFace /** Stable empty list so a session with no jobs keeps one array identity. */ const NO_JOBS: readonly JobView[] = [] -/** Keyboard-reachable controls inside the list, in document order. */ -const FOCUSABLE = 'button:not(:disabled), a[href], [tabindex]:not([tabindex="-1"])' - /** How long an armed kill waits for its confirming press before disarming. */ const KILL_ARM_MS = 3_000 @@ -314,31 +309,21 @@ function JobItem({ job, view, expanded, now, onToggle, kill, t }: { } /** - * Session-header entry point for this session's background jobs. Mounting it - * keeps the session's roster stream open; it renders nothing at all until the - * session can see at least one job. Expanding an observable row (a live job, - * or a settled one with retained output) starts its observation stream, and - * collapsing (or closing the popover) stops it — output only flows while - * someone is watching. A running row carries a two-press stop button that - * requests a human kill through the job controller. Non-touch hover on a - * text-visible trigger opens after 150ms and closes after 120ms outside both - * trigger and portal. Compact triggers toggle on click; ArrowDown opens and - * pins either layout. Interacting inside also pins the menu until explicit - * dismissal; timers and the pin are local to the mounted session. + * Session panel section for this session's background jobs. Mounting it keeps + * the session's roster stream open; it renders nothing until the session can + * see at least one job, so the panel hides the section with its title. Live + * rows come first; settled rows fold under a count that expands and clears + * client-side. Expanding an observable row (a live job, or a settled one with + * retained output) starts its observation stream, and collapsing stops it — + * output only flows while someone is watching. A running row carries a + * two-press stop button that requests a human kill through the job controller. * @param props - runtime slot currency, the jobs snapshot hook, the roster, * observation, and kill controls, and the namespace translator. - * @returns the trigger and its popover list, or null when there is nothing to show. + * @returns the job list, or null when there is nothing to show. */ -export function JobListAction({ sessionId, useJobs, watchRows, observe, killJob, t }: JobListActionProps) { - const activityId = useId() +export function JobsSection({ sessionId, useJobs, watchRows, observe, killJob, t }: JobsSectionProps) { const jobs = useJobs(state => state.rows[sessionId]) ?? NO_JOBS const observedViews = useJobs(state => state.observed) - const [menuState, setMenuState] = useState<{ sessionId: SessionId; mode: 'closed' | 'hover' | 'pinned' }>( - { sessionId, mode: 'closed' }, - ) - const hoverOpenTimer = useRef | undefined>(undefined) - const hoverCloseTimer = useRef | undefined>(undefined) - if (menuState.sessionId !== sessionId) setMenuState({ sessionId, mode: 'closed' }) const [expandedKey, setExpandedKey] = useState(undefined) const [now, setNow] = useState(() => Date.now()) // Settled-section fold: an explicit user toggle wins; before one, the tail @@ -349,10 +334,6 @@ export function JobListAction({ sessionId, useJobs, watchRows, observe, killJob, const [clearedKeys, setClearedKeys] = useState>(() => new Set()) // One kill affordance advances at a time: arming a row disarms any other. const [killPhase, setKillPhase] = useState<{ key: string; state: Exclude } | undefined>(undefined) - const rootRef = useRef(null) - const triggerRef = useRef(null) - const countRef = useRef(null) - const menuRef = useRef(null) const rows = useMemo(() => ordered(jobs), [jobs]) const liveRows = useMemo(() => rows.filter(isLive), [rows]) @@ -361,101 +342,27 @@ export function JobListAction({ sessionId, useJobs, watchRows, observe, killJob, [rows, clearedKeys], ) const settledExpanded = settledOpen ?? liveRows.length === 0 - const visibleCount = liveRows.length + settledRows.length - const hasJobs = visibleCount > 0 - const open = hasJobs && menuState.sessionId === sessionId && menuState.mode !== 'closed' - const cancelHover = useCallback((): void => { - clearTimeout(hoverOpenTimer.current) - clearTimeout(hoverCloseTimer.current) - hoverOpenTimer.current = undefined - hoverCloseTimer.current = undefined - }, []) - - const changeOpen = useCallback((next: boolean): void => { - cancelHover() - if (next) setNow(Date.now()) - setMenuState({ sessionId, mode: next ? 'pinned' : 'closed' }) - }, [cancelHover, sessionId]) - - // CSS owns the compact breakpoint; read its result only for pointer gestures. - const allowsHoverOpen = (): boolean => countRef.current !== null - && getComputedStyle(countRef.current).display !== 'none' - - const hoverEnter = (event: PointerEvent): void => { - if (event.pointerType === 'touch') return - cancelHover() - if (open || !allowsHoverOpen()) return - hoverOpenTimer.current = setTimeout(() => { - hoverOpenTimer.current = undefined - if (!allowsHoverOpen()) return - setNow(Date.now()) - setMenuState({ sessionId, mode: 'hover' }) - }, 150) - } - - const hoverLeave = (event: PointerEvent): void => { - if (event.pointerType === 'touch') return - cancelHover() - if (!open || menuState.mode === 'pinned') return - hoverCloseTimer.current = setTimeout(() => { - hoverCloseTimer.current = undefined - setMenuState({ sessionId, mode: 'closed' }) - }, 120) - } - - // Timers belong to this mounted session and cannot survive a disappearing trigger. - useEffect(() => cancelHover, [cancelHover, sessionId, hasJobs]) - - const anchorName = `--dsh-jobs-${useId().replaceAll(':', '')}` - useDismissOnOutsidePointer(rootRef, open, changeOpen, menuRef) - // Hover does not move focus; Escape must also work from the rest of the page. - useEffect(() => { - if (!open) return - const dismiss = (event: globalThis.KeyboardEvent): void => { - if (event.key !== 'Escape' || event.defaultPrevented) return - event.preventDefault() - changeOpen(false) - } - document.addEventListener('keydown', dismiss) - return () => { document.removeEventListener('keydown', dismiss) } - }, [open, changeOpen]) - - // The roster follows the mounted session: one stream while this control - // lives, released with it. + // The roster follows the mounted section: one stream while it lives, released with it. useEffect(() => watchRows(sessionId), [sessionId, watchRows]) - // The clock only runs while an open list is showing something that moves. + // The clock only runs while the list shows something that moves. useEffect(() => { - if (!open || liveRows.length === 0) return + if (liveRows.length === 0) return setNow(Date.now()) const timer = setInterval(() => { setNow(Date.now()) }, 1_000) return () => { clearInterval(timer) } - }, [open, liveRows.length]) + }, [liveRows.length]) // Observation follows visibility: the stream opens when an observable panel - // expands and closes when it collapses, unmounts, or the popover closes. - const expandedRow = open && expandedKey !== undefined - ? rows.find(job => String(job.id) === expandedKey) - : undefined + // expands and closes when it collapses or the section unmounts. + const expandedRow = expandedKey === undefined ? undefined : rows.find(job => String(job.id) === expandedKey) const activeJob = expandedRow !== undefined && isObservable(expandedRow) ? expandedRow.id : undefined useEffect(() => { if (activeJob === undefined) return return observe(sessionId, activeJob) }, [sessionId, activeJob, observe]) - // A returning roster starts closed rather than restoring an obsolete pin. - useEffect(() => { - if (!hasJobs) changeOpen(false) - }, [hasJobs, changeOpen]) - - // An expanded row that left the list (owner disposal) folds its panel. - useEffect(() => { - if (expandedKey !== undefined && !rows.some(job => String(job.id) === expandedKey)) { - setExpandedKey(undefined) - } - }, [rows, expandedKey]) - // An armed kill disarms on a timer, and a failed one clears its hint; the // pending phase instead waits for the RPC (or the row's own status flip). // The cleanup clears the timer on every phase change, so a firing timer @@ -471,12 +378,9 @@ export function JobListAction({ sessionId, useJobs, watchRows, observe, killJob, // A phase whose row stopped being killable (settled, stopping, removed) // has no button to describe any more. - useEffect(() => { - if (killPhase !== undefined - && !rows.some(job => String(job.id) === killPhase.key && job.status === 'running')) { - setKillPhase(undefined) - } - }, [rows, killPhase]) + const killable = killPhase !== undefined + && rows.some(job => String(job.id) === killPhase.key && job.status === 'running') + if (killPhase !== undefined && !killable) setKillPhase(undefined) const pressKill = (job: JobView): void => { const key = String(job.id) @@ -490,17 +394,14 @@ export function JobListAction({ sessionId, useJobs, watchRows, observe, killJob, // frames (control stream) have no cross-carrier ordering, so re-enabling // here could offer a duplicate kill while the row still reads `running`. // The authoritative jobs frame flips the row to `stopping`, which removes - // the button and clears the phase through the killable-set effect above. + // the button and clears the phase above. setKillPhase(current => current?.key === key && !ok ? { key, state: 'failed' } : current) }) } - if (visibleCount === 0) return null - - const count = liveRows.length > 0 ? liveRows.length : visibleCount - const countLabel = t(count === 1 ? 'count.idle.one' : 'count.idle.other', { count }) + if (liveRows.length + settledRows.length === 0) return null const clearSettled = (): void => { setClearedKeys((current) => { @@ -513,35 +414,6 @@ export function JobListAction({ sessionId, useJobs, watchRows, observe, killJob, } } - // The portaled list sits at the end of the document, so Tab is bridged to - // keep the in-place order: the trigger leads into the list, and leaving - // either end of the list returns to the trigger's position in the page. - const onKeyDown = (event: KeyboardEvent): void => { - const trigger = triggerRef.current - if (event.key === 'Escape') { - event.preventDefault() - changeOpen(false) - trigger?.focus() - return - } - if (!open) return - const menu = menuRef.current - /* v8 ignore next -- both refs are attached while the open list renders. */ - if (event.key !== 'Tab' || trigger === null || menu === null) return - const focusable = [...menu.querySelectorAll(FOCUSABLE)] - if (event.target === trigger) { - // Every list carries a control: a live row's toggle or the settled section's buttons. - if (event.shiftKey) return - event.preventDefault() - focusable[0]?.focus() - } else if (event.shiftKey ? event.target === focusable[0] : event.target === focusable.at(-1)) { - // Shift+Tab lands on the trigger itself; Tab continues from it to the - // control that follows the trigger. - if (event.shiftKey) event.preventDefault() - trigger.focus() - } - } - const item = (job: JobView) => ( - - - - {liveRows.length > 0 && } - {open - ? createPortal( - { changeOpen(true) }} - onFocusCapture={() => { changeOpen(true) }} - > -
    - {liveRows.length > 0 - ? - : null} - {liveRows.map(item)} - {settledRows.length > 0 - ? ( -
  • - - -
  • - ) - : null} - {settledExpanded ? settledRows.map(item) : null} -
-
, - document.body, +
    + {liveRows.map(item)} + {settledRows.length > 0 + ? ( +
  • + + +
  • ) : null} - + {settledExpanded ? settledRows.map(item) : null} +
) } diff --git a/packages/client/ui-jobs/src/client/index.ts b/packages/client/ui-jobs/src/client/index.ts index 5174aa1fb8..8bc214bccc 100644 --- a/packages/client/ui-jobs/src/client/index.ts +++ b/packages/client/ui-jobs/src/client/index.ts @@ -1,17 +1,18 @@ /** - * Background-job plugin, browser half: contributes one session-header action - * that renders this session's jobs. Job rows, per-row observation streams, - * and the human kill all go through the `jobs` client service; this plugin - * holds no transport state of its own. + * Background-job plugin, browser half: contributes the Session panel's + * background-jobs section. Job rows, per-row observation streams, and the + * human kill all go through the `jobs` client service; this plugin holds no + * transport state of its own. */ import type { Context as ClientContext } from '@deepseek-ai/cordis' import type { JobId } from '@deepseek-ai/dsh-jobs/brand' -import { JobListAction } from './JobListAction.tsx' -import type { JobListInjected } from './JobListAction.tsx' +import { JobsSection } from './JobsSection.tsx' +import type { JobsSectionInjected } from './JobsSection.tsx' import type {} from '@deepseek-ai/dsh-api-job-controller/client' import type {} from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type {} from '@deepseek-ai/dsh-client-ui-session/client' +import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client' import { en, ja, es, fr, de, ru, pt, NS, zh, type JobKey } from './locales.ts' declare module '@deepseek-ai/dsh-client-ui-slots' { @@ -21,26 +22,28 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { } } -export type { JobListActionProps, JobListInjected } from './JobListAction.tsx' +export type { JobsSectionProps, JobsSectionInjected } from './JobsSection.tsx' /** Required services: the jobs rosters, observations, and kill, the slot registry, and dictionaries. */ export const inject = ['jobs', 'slots', 'locale'] /** - * Client plugin body: register the dictionaries and the header action. + * Client plugin body: register the dictionaries and the Session panel section. * @param ctx - client root context. */ export function apply(ctx: ClientContext): void { ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'ui-jobs: dictionaries') + const t = ctx.locale.bind(NS) ctx.slots.inject( - 'conversation.session.header.actions', + 'conversation.session.panel.section', () => ctx.slots.register({ - name: 'conversation.session.header.actions', - id: 'job-list', - // Background work follows the preset label in the header actions band. - order: 20, + name: 'conversation.session.panel.section', + id: 'background-jobs', + // After change requests (100) and subagents (200). + order: 300, + label: () => t('list.aria'), locale: NS, - inject: (): JobListInjected => ({ + inject: (): JobsSectionInjected => ({ hooks: { jobs: ctx.jobs.state }, watchRows: sessionId => ctx.jobs.watchRows(sessionId), observe: (sessionId, id) => ctx.jobs.observe(sessionId, id), @@ -48,6 +51,6 @@ export function apply(ctx: ClientContext): void { // roster stream delivered, so the wire boundary stamps it back here. killJob: async (sessionId, jobId) => (await ctx.jobs.kill(sessionId, jobId as JobId)).ok, }), - }, JobListAction), + }, JobsSection), ) } diff --git a/packages/client/ui-jobs/src/client/locales.ts b/packages/client/ui-jobs/src/client/locales.ts index c968a08b5d..4d48f159e3 100644 --- a/packages/client/ui-jobs/src/client/locales.ts +++ b/packages/client/ui-jobs/src/client/locales.ts @@ -5,10 +5,7 @@ export const NS = 'job' /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { - 'count.idle.one': '{count} 个后台任务', - 'count.idle.other': '{count} 个后台任务', 'list.aria': '后台任务', - 'section.live': '进行中', 'section.settledCount': '已结束 {count}', 'section.clear': '清空', 'row.expandAria': '展开 {label} 的实时输出', @@ -47,10 +44,7 @@ export const zh = { /** English dictionary, key-identical to the Chinese source of truth. */ export const en: Record = { - 'count.idle.one': '{count} background job', - 'count.idle.other': '{count} background jobs', 'list.aria': 'Background jobs', - 'section.live': 'Running', 'section.settledCount': 'Finished {count}', 'section.clear': 'Clear', 'row.expandAria': 'Show live output of {label}', @@ -92,10 +86,7 @@ export type JobKey = keyof typeof zh /** Japanese copy, checked against the English keys. */ export const ja = { - 'count.idle.one': 'バックグラウンドジョブ {count} 件', - 'count.idle.other': 'バックグラウンドジョブ {count} 件', 'list.aria': 'バックグラウンドジョブ', - 'section.live': '実行中', 'section.settledCount': '完了 {count} 件', 'section.clear': 'クリア', 'row.expandAria': '{label} のライブ出力を表示', @@ -134,10 +125,7 @@ export const ja = { /** Spanish dictionary, checked against the English keys. */ export const es = { - 'count.idle.one': 'Tareas en segundo plano: {count}', - 'count.idle.other': 'Tareas en segundo plano: {count}', 'list.aria': 'Trabajos en segundo plano', - 'section.live': 'corriendo', 'section.settledCount': 'Terminado {count}', 'section.clear': 'Borrar', 'row.expandAria': 'Mostrar salida en vivo de {label}', @@ -176,10 +164,7 @@ export const es = { /** French dictionary, checked against the English keys. */ export const fr = { - 'count.idle.one': 'Tâches en arrière-plan : {count}', - 'count.idle.other': 'Tâches en arrière-plan : {count}', 'list.aria': 'Travaux en arrière-plan', - 'section.live': 'Courir', 'section.settledCount': 'Terminé {count}', 'section.clear': 'Effacer', 'row.expandAria': 'Afficher la sortie en direct de {label}', @@ -218,10 +203,7 @@ export const fr = { /** German dictionary, checked against the English keys. */ export const de = { - 'count.idle.one': 'Hintergrundaufgaben: {count}', - 'count.idle.other': 'Hintergrundaufgaben: {count}', 'list.aria': 'Hintergrundjobs', - 'section.live': 'Laufen', 'section.settledCount': 'Fertig {count}', 'section.clear': 'Klar', 'row.expandAria': 'Live-Ausgabe von {label} anzeigen', @@ -260,10 +242,7 @@ export const de = { /** Russian dictionary, checked against the English keys. */ export const ru = { - 'count.idle.one': 'Фоновые задачи: {count}', - 'count.idle.other': 'Фоновые задачи: {count}', 'list.aria': 'Фоновые задания', - 'section.live': 'Бег', 'section.settledCount': 'Закончено {count}', 'section.clear': 'Очистить', 'row.expandAria': 'Показать живой вывод {label}', @@ -302,10 +281,7 @@ export const ru = { /** Portuguese dictionary, checked against the English keys. */ export const pt = { - 'count.idle.one': 'Tarefas em segundo plano: {count}', - 'count.idle.other': 'Tarefas em segundo plano: {count}', 'list.aria': 'Trabalhos em segundo plano', - 'section.live': 'Correndo', 'section.settledCount': 'Concluído {count}', 'section.clear': 'Limpar', 'row.expandAria': 'Mostrar saída ao vivo de {label}', diff --git a/packages/client/ui-jobs/tests/browser-plugin.client.spec.ts b/packages/client/ui-jobs/tests/browser-plugin.client.spec.ts index 1a393d7bf2..b66e5ab29a 100644 --- a/packages/client/ui-jobs/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-jobs/tests/browser-plugin.client.spec.ts @@ -9,17 +9,18 @@ import { JobId } from '@deepseek-ai/dsh-jobs/brand' import { SessionId } from '@deepseek-ai/dsh-session/types' import { describe, expect, it } from 'vitest' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' import { stubConfigForm } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyLocale, inject as localeInject } from '@deepseek-ai/dsh-client-locale/client' import { apply, inject } from '../src/client/index.ts' -import type { JobListInjected } from '../src/client/JobListAction.tsx' +import type { JobsSectionInjected } from '../src/client/JobsSection.tsx' import { apply as applyNode } from '../src/index.ts' import { en, NS, zh } from '../src/client/locales.ts' -/** Slot ledger reader: entry ids currently registered in the header list. */ -function headerEntryIds(ctx: Context): (string | undefined)[] { +/** Slot ledger reader: entry ids currently registered in the Session panel section list. */ +function sectionEntryIds(ctx: Context): (string | undefined)[] { return ctx.slots - .entries('conversation.session.header.actions') + .entries('conversation.session.panel.section') .map(entry => entry.options.id) } @@ -39,7 +40,7 @@ async function bench(): Promise<{ ctx: Context; fiber: ReturnType null) ctx.provide('jobs', { @@ -80,10 +81,10 @@ describe('ui-jobs browser half', () => { it('exposes the jobs source and the roster, observation, and kill controls through the inject face', async () => { const { ctx } = await bench() const entry = ctx.slots - .entries('conversation.session.header.actions') - .find(candidate => candidate.options.id === 'job-list') - const inject = entry?.inject as (() => JobListInjected) | undefined - if (inject === undefined) throw new Error('job-list entry registered no inject face') + .entries('conversation.session.panel.section') + .find(candidate => candidate.options.id === 'background-jobs') + const inject = entry?.inject as (() => JobsSectionInjected) | undefined + if (inject === undefined) throw new Error('background-jobs entry registered no inject face') const face = inject() expect(face.hooks.jobs).toBeDefined() const release = face.watchRows(SessionId('session')) @@ -102,11 +103,14 @@ describe('ui-jobs browser half', () => { expect(kills).toEqual([['sess-live', 'bash-3'], ['sess-live', 'bash-4']]) }) - it('registers the header action, and fiber teardown removes it (HMR safety)', async () => { + it('registers the Session panel section, and fiber teardown removes it (HMR safety)', async () => { const { ctx, fiber } = await bench() - expect(headerEntryIds(ctx)).toContain('job-list') + expect(sectionEntryIds(ctx)).toContain('background-jobs') + const entry = ctx.slots.entries('conversation.session.panel.section').find(candidate => candidate.options.id === 'background-jobs') + expect(entry?.options.order).toBe(300) + expect(resolveSlotLabel(entry?.options.label)).toBe(zh['list.aria']) await fiber.dispose() - expect(headerEntryIds(ctx)).not.toContain('job-list') + expect(sectionEntryIds(ctx)).not.toContain('background-jobs') }) it('registers both dictionaries under its own namespace and releases them with the fiber', async () => { diff --git a/packages/client/ui-jobs/tests/job-list-action.client.spec.tsx b/packages/client/ui-jobs/tests/job-list-action.client.spec.tsx deleted file mode 100644 index 5bbf91ace5..0000000000 --- a/packages/client/ui-jobs/tests/job-list-action.client.spec.tsx +++ /dev/null @@ -1,950 +0,0 @@ -// @vitest-environment jsdom -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' -import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' -import type { JobsSnapshot, JobView, ObservedJob } from '@deepseek-ai/dsh-api-job-controller/client' -import type { SessionId } from '@deepseek-ai/dsh-session/types' -import { JobListAction, type JobListActionProps } from '../src/client/JobListAction.tsx' -import { zh, en, ja, es, fr, de, ru, pt } from '../src/client/locales.ts' - -beforeEach(() => { - class TooltipObserver implements ResizeObserver { - constructor(private readonly callback: ResizeObserverCallback) {} - observe(target: Element): void { - const size = { inlineSize: 160, blockSize: 30 } - this.callback([{ - target, borderBoxSize: [size], contentBoxSize: [size], devicePixelContentBoxSize: [size], contentRect: new DOMRect(), - }], this) - } - unobserve(): void {} - disconnect(): void {} - } - vi.stubGlobal('ResizeObserver', TooltipObserver) - vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true }))) -}) - -beforeEach(() => { - vi.stubGlobal('CSS', { supports: (property: string) => property === '-webkit-backdrop-filter' }) -}) - -afterEach(() => { - cleanup() - vi.restoreAllMocks() - vi.unstubAllGlobals() - vi.useRealTimers() -}) - -const SESSION = 'session' as SessionId -const t: JobListActionProps['t'] = makeTranslate(zh) - -/** A running job with nothing retained yet. */ -function job(over: Partial = {}): JobView { - return { - id: 'bash-1' as JobView['id'], - kind: 'bash', - label: 'pnpm run build', - status: 'running', - startedAt: 1_700_000_000_000, - output: { total: 0, earliest: 0 }, - ...over, - } -} - -/** A job that left retained output behind, so its row offers a panel even once settled. */ -function outputJob(over: Partial = {}): JobView { - return job({ output: { total: 12, earliest: 0 }, ...over }) -} - -function props( - jobs: readonly JobView[], - observe: JobListActionProps['observe'] = () => () => {}, - observed: Readonly> = {}, - killJob: JobListActionProps['killJob'] = async () => true, - watchRows: JobListActionProps['watchRows'] = () => () => {}, -): JobListActionProps { - const jobsState: JobsSnapshot = { rows: jobs.length > 0 ? { [SESSION]: jobs } : {}, observed } - function useJobs(select: (value: JobsSnapshot) => T): T { - return select(jobsState) - } - return { sessionId: SESSION, useJobs, watchRows, observe, killJob, t } as JobListActionProps -} - -function openList(): void { - fireEvent.click(screen.getAllByRole('button')[0]!) -} - -describe('JobListAction count copy', () => { - it.each([ - [zh, '1 个后台任务', '2 个后台任务'], - [en, '1 background job', '2 background jobs'], - [ja, 'バックグラウンドジョブ 1 件', 'バックグラウンドジョブ 2 件'], - [es, 'Tareas en segundo plano: 1', 'Tareas en segundo plano: 2'], - [fr, 'Tâches en arrière-plan : 1', 'Tâches en arrière-plan : 2'], - [de, 'Hintergrundaufgaben: 1', 'Hintergrundaufgaben: 2'], - [ru, 'Фоновые задачи: 1', 'Фоновые задачи: 2'], - [pt, 'Tarefas em segundo plano: 1', 'Tarefas em segundo plano: 2'], - ] as const)('uses neutral count copy for live and settled jobs in locale %#', (dictionary, one, two) => { - const translate: JobListActionProps['t'] = makeTranslate(dictionary) - const settled = job({ id: 'settled' as JobView['id'], status: 'completed', finishedAt: 1_700_000_003_000 }) - const { rerender } = render() - expect(screen.getByRole('button', { name: one, description: dictionary['section.live'] })).toBeDefined() - rerender() - expect(screen.getByRole('button', { name: one, description: dictionary['section.live'] })).toBeDefined() - rerender() - expect(screen.getByRole('button', { name: two, description: '' })).toBeDefined() - }) -}) - -describe('JobListAction visibility', () => { - it('renders nothing while the session sees no jobs', () => { - const { container } = render() - expect(container.innerHTML).toBe('') - }) - - it('watches the session roster while mounted and releases it on unmount', () => { - const stop = vi.fn() - const watchRows = vi.fn(() => stop) - const { unmount } = render() - expect(watchRows).toHaveBeenCalledWith(SESSION) - expect(stop).not.toHaveBeenCalled() - unmount() - expect(stop).toHaveBeenCalledTimes(1) - }) - - it('counts live jobs on the trigger', () => { - render() - expect(screen.getByRole('button', { name: '2 个后台任务' })).toBeDefined() - }) - - it('retains the compact Layers icon through running, stopping, and idle states without a root chevron', () => { - const { rerender } = render() - const trigger = screen.getByRole('button') - expect(trigger.querySelector('[data-icon="dsw-icon-layers-outline-regular"]')).not.toBeNull() - expect(trigger.querySelector('[data-state="ongoing"]')).not.toBeNull() - expect(trigger.querySelector('[data-icon="dsw-icon-chevron-down-outline-regular"]')).toBeNull() - rerender() - expect(screen.getByRole('button')).toBe(trigger) - expect(trigger.querySelector('[data-state="ongoing"]')).not.toBeNull() - rerender() - expect(screen.getByRole('button')).toBe(trigger) - expect(trigger.querySelector('[data-state="ongoing"]')).toBeNull() - const icon = trigger.querySelector('[data-icon="dsw-icon-layers-outline-regular"]') - expect(icon?.getAttribute('width')).toBe('14') - expect(trigger.querySelectorAll('svg')).toHaveLength(1) - }) - - it('falls back to the total when nothing is live', () => { - render() - expect(screen.getByRole('button', { name: '1 个后台任务' })).toBeDefined() - }) -}) - -describe('JobListAction hover', () => { - function pointer(target: Element, type: 'pointerover' | 'pointerout', pointerType = 'mouse'): void { - // jsdom lacks PointerEvent; preserve its pointer type on the native event. - const event = new MouseEvent(type, { bubbles: true }) - Object.defineProperty(event, 'pointerType', { value: pointerType }) - fireEvent(target, event) - } - - function advance(ms: number): void { - act(() => { vi.advanceTimersByTime(ms) }) - } - - function hoverOpen(): HTMLElement { - const trigger = screen.getByRole('button', { name: '1 个后台任务' }) - pointer(trigger, 'pointerover') - advance(149) - expect(screen.queryByRole('list')).toBeNull() - advance(1) - expect(trigger.getAttribute('aria-expanded')).toBe('true') - return trigger - } - - it('keeps the compact trigger click-only and shows its count tooltip after 500ms', () => { - vi.useFakeTimers() - render() - const trigger = screen.getByRole('button') - const count = trigger.querySelector('[data-job-count]')! - count.style.display = 'none' - pointer(trigger, 'pointerover') - advance(499) - expect(screen.queryByRole('list')).toBeNull() - expect(screen.queryByRole('tooltip')).toBeNull() - advance(1) - expect(screen.getByRole('tooltip').textContent).toBe('1 个后台任务') - fireEvent.click(trigger) - expect(screen.queryByRole('tooltip')).toBeNull() - pointer(trigger, 'pointerout') - advance(500) - expect(screen.getByRole('list')).toBeDefined() - fireEvent.click(trigger) - expect(screen.queryByRole('list')).toBeNull() - }) - - it('cancels pending wide hover when CSS hides the count and compact clicks close hover-opened lists', () => { - vi.useFakeTimers() - render() - const trigger = screen.getByRole('button') - const count = trigger.querySelector('[data-job-count]')! - pointer(trigger, 'pointerover') - advance(100) - count.style.display = 'none' - advance(50) - expect(screen.queryByRole('list')).toBeNull() - pointer(trigger, 'pointerout') - count.style.display = '' - hoverOpen() - count.style.display = 'none' - fireEvent.click(trigger) - expect(screen.queryByRole('list')).toBeNull() - }) - - it('shows count on keyboard focus immediately and opens and pins with ArrowDown', async () => { - vi.useFakeTimers() - render() - const trigger = screen.getByRole('button') - trigger.querySelector('[data-job-count]')!.style.display = 'none' - fireEvent.keyDown(document.body, { key: 'Tab' }) - act(() => { trigger.focus() }) - expect(screen.getByRole('tooltip').textContent).toBe('1 个后台任务') - fireEvent.keyDown(trigger, { key: 'ArrowDown' }) - await act(async () => { vi.runAllTicks() }) - expect(screen.queryByRole('tooltip')).toBeNull() - const row = screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }) - expect(document.activeElement).toBe(row) - pointer(trigger, 'pointerout') - advance(120) - expect(screen.getByRole('list')).toBeDefined() - fireEvent.keyDown(row, { key: 'Escape' }) - expect(screen.queryByRole('list')).toBeNull() - expect(document.activeElement).toBe(trigger) - }) - - it('waits for hover, bridges the portal gap, and closes after leaving both surfaces', () => { - vi.useFakeTimers() - const observe = vi.fn(() => () => {}) - const { container } = render() - const trigger = hoverOpen() - const menu = screen.getByRole('list').parentElement! - expect(container.contains(menu)).toBe(false) - expect(observe).not.toHaveBeenCalled() - pointer(trigger, 'pointerout') - advance(119) - pointer(menu, 'pointerover') - advance(120) - expect(screen.getByRole('list')).toBeDefined() - pointer(menu, 'pointerout') - advance(119) - expect(screen.getByRole('list')).toBeDefined() - advance(1) - expect(screen.queryByRole('list')).toBeNull() - }) - - it('cancels short hover and preserves a returning pointer during leave grace', () => { - vi.useFakeTimers() - render() - const trigger = screen.getByRole('button') - pointer(trigger, 'pointerover') - advance(149) - pointer(trigger, 'pointerout') - advance(150) - expect(screen.queryByRole('list')).toBeNull() - hoverOpen() - pointer(trigger, 'pointerout') - advance(100) - pointer(trigger, 'pointerover') - advance(120) - expect(screen.getByRole('list')).toBeDefined() - }) - - it('pins a hover-opened list on click until explicit dismissal', () => { - vi.useFakeTimers() - render() - const trigger = hoverOpen() - fireEvent.click(trigger) - pointer(trigger, 'pointerout') - advance(120) - expect(screen.getByRole('list')).toBeDefined() - fireEvent.click(trigger) - expect(screen.queryByRole('list')).toBeNull() - hoverOpen() - fireEvent.click(trigger) - fireEvent.pointerDown(document.body) - expect(screen.queryByRole('list')).toBeNull() - hoverOpen() - pointer(trigger, 'pointerout') - advance(120) - expect(screen.queryByRole('list')).toBeNull() - }) - - it('ignores touch hover while keeping tap usable', () => { - vi.useFakeTimers() - render() - const trigger = screen.getByRole('button') - pointer(trigger, 'pointerover', 'touch') - advance(150) - expect(screen.queryByRole('list')).toBeNull() - fireEvent.click(trigger) - pointer(trigger, 'pointerout', 'touch') - advance(120) - expect(screen.getByRole('list')).toBeDefined() - fireEvent.click(trigger) - expect(screen.queryByRole('list')).toBeNull() - }) - - it('pins keyboard focus and releases expanded output on Escape or hover close', () => { - vi.useFakeTimers() - const stop = vi.fn() - const observe = vi.fn(() => stop) - render() - const trigger = hoverOpen() - pointer(trigger, 'pointerout') - act(() => { trigger.focus() }) - fireEvent.keyDown(trigger, { key: 'Tab' }) - const row = screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }) - expect(document.activeElement).toBe(row) - advance(120) - fireEvent.click(row) - expect(observe).toHaveBeenCalledTimes(1) - fireEvent.keyDown(row, { key: 'Escape' }) - expect(document.activeElement).toBe(trigger) - expect(stop).toHaveBeenCalledTimes(1) - hoverOpen() - expect(observe).toHaveBeenCalledTimes(2) - pointer(trigger, 'pointerout') - advance(120) - expect(screen.queryByRole('list')).toBeNull() - expect(stop).toHaveBeenCalledTimes(2) - }) - - it('pins pointer interaction so leaving cannot interrupt stop confirmation', () => { - vi.useFakeTimers() - render() - const trigger = hoverOpen() - pointer(trigger, 'pointerout') - const stop = screen.getByTitle(zh['kill.stop'].replace('{label}', 'pnpm run build')) - fireEvent.pointerDown(stop) - fireEvent.click(stop) - pointer(screen.getByRole('list').parentElement!, 'pointerout') - advance(120) - expect(stop.getAttribute('data-kill-state')).toBe('armed') - expect(screen.getByRole('list')).toBeDefined() - }) - - it('dismisses a hover-opened list with Escape while focus is elsewhere', () => { - vi.useFakeTimers() - render() - hoverOpen() - fireEvent.keyDown(document.body, { key: 'a' }) - expect(screen.getByRole('list')).toBeDefined() - fireEvent.keyDown(document.body, { key: 'Escape' }) - expect(screen.queryByRole('list')).toBeNull() - }) - - it.each(['opening', 'closing'] as const)('cleans up a pending %s timer on unmount', (phase) => { - vi.useFakeTimers() - const { unmount } = render() - const trigger = screen.getByRole('button') - pointer(trigger, 'pointerover') - if (phase === 'closing') { - advance(150) - pointer(trigger, 'pointerout') - } - unmount() - expect(vi.getTimerCount()).toBe(0) - advance(150) - expect(screen.queryByRole('list')).toBeNull() - }) - - it('releases expanded output and pending hover close before showing another session', () => { - vi.useFakeTimers() - const stop = vi.fn() - const observe = vi.fn(() => stop) - const first = props([outputJob()], observe) - const { rerender } = render() - const trigger = hoverOpen() - const row = screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }) - fireEvent.click(row) - expect(observe).toHaveBeenCalledTimes(1) - pointer(trigger, 'pointerout') - const nextId = 'next-session' as SessionId - rerender( select({ rows: { [nextId]: [outputJob()] }, observed: {} })} - />) - expect(stop).toHaveBeenCalledTimes(1) - expect(observe).toHaveBeenCalledTimes(1) - expect(vi.getTimerCount()).toBe(0) - hoverOpen() - advance(120) - expect(screen.getByRole('list')).toBeDefined() - expect(observe).toHaveBeenLastCalledWith(nextId, 'bash-1') - }) - - it('cancels pending hover and clears pins on session change or an empty roster', () => { - vi.useFakeTimers() - const first = props([job()]) - const nextId = 'next-session' as SessionId - const next: JobListActionProps = { - ...first, - sessionId: nextId, - useJobs: select => select({ rows: { [nextId]: [job()] }, observed: {} }), - } - const { rerender } = render() - pointer(screen.getByRole('button'), 'pointerover') - rerender() - advance(150) - expect(screen.queryByRole('list')).toBeNull() - const trigger = hoverOpen() - fireEvent.click(trigger) - rerender() - expect(screen.queryByRole('list')).toBeNull() - pointer(screen.getByRole('button'), 'pointerover') - rerender() - advance(150) - expect(vi.getTimerCount()).toBe(0) - rerender() - hoverOpen() - fireEvent.click(screen.getByRole('button', { name: '1 个后台任务' })) - rerender() - rerender() - expect(screen.queryByRole('list')).toBeNull() - }) -}) - -describe('JobListAction rows', () => { - it('renders a settled job without retained output as a static row', () => { - render() - expect(screen.getByRole('button', { name: '1 个后台任务' })).toBeDefined() - openList() - expect(screen.getByText('explore the repo')).toBeDefined() - expect(screen.queryByRole('button', { name: zh['row.expandAria'].replace('{label}', 'explore the repo') })).toBeNull() - }) - - it('offers a panel on a live row before any output arrived', () => { - render() - openList() - expect(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'warming up') })).toBeDefined() - }) - - it('shows the live progress line in place of the status word', () => { - render() - openList() - const list = screen.getByRole('list', { name: zh['list.aria'] }) - expect(within(list).getByText('pnpm run build')).toBeDefined() - expect(within(list).getByText('winding down')).toBeDefined() - }) - - it('folds the settled tail behind its count while live work exists, and clears on demand', () => { - const settled = [job({ id: 'bash-2' as JobView['id'], label: 'settled work', status: 'completed', finishedAt: 1_700_000_012_000 })] - render() - openList() - expect(screen.getByText(zh['section.live'], { selector: 'li' })).toBeDefined() - const toggle = screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') }) - // Folded by default while something runs; the toggle expands it. - expect(toggle.getAttribute('aria-expanded')).toBe('false') - expect(screen.queryByText('settled work')).toBeNull() - fireEvent.click(toggle) - expect(screen.getByText('settled work')).toBeDefined() - // Clearing hides the tail client-side and drops the whole section line. - fireEvent.click(screen.getByRole('button', { name: zh['section.clear'] })) - expect(screen.queryByText('settled work')).toBeNull() - expect(screen.queryByRole('button', { name: zh['section.clear'] })).toBeNull() - }) - - it('opens the settled tail by default when nothing is live', () => { - render() - openList() - expect(screen.getByText('pnpm run build')).toBeDefined() - expect(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') }).getAttribute('aria-expanded')).toBe('true') - }) - - it('clearing drops an expanded settled panel with its rows', () => { - const observe = vi.fn(() => () => {}) - render() - openList() - // Nothing live: the tail is open; expand the settled row's output panel. - fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'settled work') })) - expect(observe).toHaveBeenCalledWith(SESSION, 'bash-2') - fireEvent.click(screen.getByRole('button', { name: zh['section.clear'] })) - expect(screen.queryByText('settled work')).toBeNull() - expect(screen.queryByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'settled work') })).toBeNull() - }) - - it('shows a settled duration and ticks a live one', () => { - vi.useFakeTimers({ now: 1_700_000_020_000 }) - render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '3') })) - expect(screen.getByText('5秒')).toBeDefined() - expect(screen.getByText('12秒')).toBeDefined() - expect(screen.getByText('1小时3分')).toBeDefined() - expect(screen.getByText('1分12秒')).toBeDefined() - act(() => { vi.advanceTimersByTime(1_000) }) - expect(screen.getByText('6秒')).toBeDefined() - }) - - it('lists rows with kind, label, and detail-or-status', () => { - render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') })) - const list = screen.getByRole('list', { name: zh['list.aria'] }) - const items = within(list).getAllByRole('listitem') - // The section line is a listitem too now: live row, section, settled row. - expect(items).toHaveLength(3) - expect(items[0]?.textContent).toContain('pnpm run build') - // A live row's second line is kind · duration; the status word only - // appears through a detail (none while running). - expect(items[0]?.textContent).toMatch(/小时|分|秒/) - expect(items[2]?.textContent).toContain('exit code: 3') - }) - - it('orders live rows first by start and settled rows newest-first with tie-breaks', () => { - const settled = (id: string, label: string, startedAt: number, finishedAt?: number): JobView => - job({ - id: id as JobView['id'], - label, - status: 'completed', - startedAt, - ...finishedAt !== undefined ? { finishedAt } : {}, - }) - render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '5') })) - const labels = within(screen.getByRole('list', { name: zh['list.aria'] })) - .getAllByRole('listitem') - .map(item => item.querySelector('[title]')?.getAttribute('title')) - .filter((title): title is string => title != null && !title.startsWith('已运行') && !title.startsWith('耗时')) - expect(labels).toEqual([ - 'live-2', 'live-1', 'settled-d', 'settled-a', 'settled-c', 'settled-b', 'settled-e', - ]) - expect(screen.getAllByText(zh['status.completed']).length).toBeGreaterThan(0) - }) - - it('breaks a settled tie on start order so map iteration never decides it', () => { - render() - openList() - expect(within(screen.getByRole('list')).getAllByRole('listitem').map(row => row.querySelector('[title]')?.getAttribute('title')).filter(title => title !== undefined)) - .toEqual(['first', 'second']) - }) - - it('prefers the producer detail over the generic status word', () => { - render() - openList() - expect(within(screen.getByRole('list')).getByText('signal: SIGTERM')).toBeDefined() - }) - - it('renders settled status words and every lifecycle indicator', () => { - render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '3') })) - for (const word of ['已完成', '已取消', '已失败']) { - expect(within(screen.getByRole('list')).getByText(word)).toBeDefined() - } - expect([...screen.getByRole('list').querySelectorAll('li [data-state]')].map(node => node.getAttribute('data-state'))) - .toEqual(['ongoing', 'warning', 'done', 'warning', 'error']) - }) -}) - -describe('JobListAction observation', () => { - it('marks killed rows, renders every output line unfolded, and copies the command', async () => { - const writeText = vi.fn().mockResolvedValue(undefined) - Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) - const lines = Array.from({ length: 24 }, (_value, index) => `line ${index + 1}`).join('\n') - const view: ObservedJob = { - jobId: 'bash-1' as JobView['id'], - text: lines, - gapBefore: false, - streaming: false, - } - render() - openList() - expect(screen.getByText(zh['status.killed'])).toBeDefined() - fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) - // The panel scrolls instead of folding: every line renders, no fold control. - expect(screen.getByText('line 1')).toBeDefined() - expect(screen.getByText('line 24')).toBeDefined() - expect(screen.queryByRole('button', { name: zh['terminal.expandAria'].replace('{n}', '8') })).toBeNull() - // The panel draws no state dot or label of its own — the row carries it. - expect(screen.queryByText(zh['terminal.done'])).toBeNull() - // The copy control carries the command, not the output. - await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['terminal.copy'] })) }) - expect(writeText).toHaveBeenCalledWith('pnpm run build') - }) - - it('anchors the portaled list with CSS without reading geometry on resize or ancestor scroll', () => { - const { container } = render() - const trigger = screen.getByRole('button', { name: '1 个后台任务' }) - const anchor = trigger.closest('div')! - const measure = vi.spyOn(anchor, 'getBoundingClientRect') - fireEvent.click(trigger) - const list = screen.getByRole('list', { name: zh['list.aria'] }) - const menu = list.closest('[data-menu-material]')! - expect(menu.parentElement).toBe(document.body) - expect(container.contains(list)).toBe(false) - expect(anchor.style.anchorName).not.toBe('') - expect(menu.style.positionAnchor).toBe(anchor.style.anchorName) - expect(menu.style.left).toBe('') - expect(menu.style.top).toBe('') - fireEvent(window, new Event('resize')) - fireEvent.scroll(container) - expect(menu.style.positionAnchor).toBe(anchor.style.anchorName) - expect(measure).not.toHaveBeenCalled() - }) - - it('gives independent job controls separate CSS anchors', () => { - render(<>) - const triggers = screen.getAllByRole('button', { name: '1 个后台任务' }) - const first = triggers[0]!.closest('div')! - const second = triggers[1]!.closest('div')! - expect(first.style.anchorName).not.toBe('') - expect(second.style.anchorName).not.toBe('') - expect(first.style.anchorName).not.toBe(second.style.anchorName) - }) - - it('keeps visual viewport changes out of inline placement and closes normally', () => { - const viewport = Object.assign(new EventTarget(), { width: 600, height: 500, offsetLeft: 40, offsetTop: 60 }) - vi.stubGlobal('visualViewport', viewport) - const listen = vi.spyOn(viewport, 'addEventListener') - render() - const trigger = screen.getByRole('button', { name: '1 个后台任务' }) - fireEvent.click(trigger) - const menu = screen.getByRole('list', { name: zh['list.aria'] }).closest('[data-menu-material]')! - const placement = menu.style.positionAnchor - act(() => { - viewport.offsetLeft = 100 - viewport.offsetTop = 120 - viewport.dispatchEvent(new Event('scroll')) - viewport.height = 200 - viewport.dispatchEvent(new Event('resize')) - }) - expect(menu.style.positionAnchor).toBe(placement) - expect(menu.style.left).toBe('') - expect(menu.style.top).toBe('') - expect(menu.style.getPropertyValue('--dsh-anchored-max-width')).toBe('') - expect(menu.style.getPropertyValue('--dsh-anchored-max-height')).toBe('') - expect(listen).not.toHaveBeenCalled() - fireEvent.click(trigger) - expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull() - }) - - it('keeps portaled controls interactive and releases observation on dismissal and unmount', () => { - const stop = vi.fn() - const observe = vi.fn(() => stop) - const { container, unmount } = render() - const trigger = screen.getByRole('button', { name: '1 个后台任务' }) - trigger.focus() - fireEvent.click(trigger) - const list = screen.getByRole('list', { name: zh['list.aria'] }) - expect(container.contains(list)).toBe(false) - const row = screen.getByRole('button', { - name: zh['row.expandAria'].replace('{label}', 'pnpm run build'), - }) - fireEvent.pointerDown(row) - fireEvent.click(row) - expect(screen.getByRole('list', { name: zh['list.aria'] })).toBe(list) - expect(observe).toHaveBeenCalledTimes(1) - expect(stop).not.toHaveBeenCalled() - const kill = screen.getByTitle(zh['kill.stop'].replace('{label}', 'pnpm run build')) - fireEvent.pointerDown(kill) - fireEvent.click(kill) - expect(kill.getAttribute('data-kill-state')).toBe('armed') - expect(screen.getByRole('list', { name: zh['list.aria'] })).toBe(list) - - row.focus() - fireEvent.keyDown(row, { key: 'Escape' }) - expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull() - expect(document.activeElement).toBe(trigger) - expect(stop).toHaveBeenCalledTimes(1) - fireEvent.click(trigger) - expect(observe).toHaveBeenCalledTimes(2) - fireEvent.pointerDown(document.body) - expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull() - expect(stop).toHaveBeenCalledTimes(2) - fireEvent.click(trigger) - expect(observe).toHaveBeenCalledTimes(3) - const reopened = screen.getByRole('list', { name: zh['list.aria'] }) - unmount() - expect(document.body.contains(reopened)).toBe(false) - expect(stop).toHaveBeenCalledTimes(3) - }) - - it('ignores other keys while open and closes once the roster empties', () => { - const settledPair = [ - outputJob({ id: 'bash-1' as JobView['id'], status: 'completed', finishedAt: 2 }), - outputJob({ id: 'bash-2' as JobView['id'], status: 'completed', finishedAt: 3 }), - ] - const { rerender } = render() - expect(screen.getByRole('button', { name: '2 个后台任务' })).toBeDefined() - openList() - const list = screen.getByRole('list', { name: zh['list.aria'] }) - fireEvent.keyDown(list, { key: 'a' }) - expect(screen.getByRole('list', { name: zh['list.aria'] })).toBeDefined() - // The roster emptying unmounts the control entirely; the open flag resets first. - rerender() - expect(screen.queryByRole('button')).toBeNull() - }) - - it('starts observing on expand with the session identity, renders the live text, and stops on collapse', () => { - const stop = vi.fn() - const observe = vi.fn(() => stop) - const view: ObservedJob = { - jobId: 'bash-1' as JobView['id'], - text: 'compiling…\n', - gapBefore: false, - streaming: true, - } - render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) - expect(observe).toHaveBeenCalledWith(SESSION, 'bash-1') - expect(screen.getByText('compiling…')).toBeDefined() - - fireEvent.click(screen.getByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'pnpm run build') })) - expect(stop).toHaveBeenCalledTimes(1) - }) - - it('renders a running panel with the prompt alone for a live row whose output has not arrived', () => { - const view: ObservedJob = { - jobId: 'bash-1' as JobView['id'], - text: '', - gapBefore: false, - streaming: true, - } - render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) - expect(screen.getByRole('list', { name: zh['list.aria'] }).querySelector('[data-running]')).not.toBeNull() - expect(screen.queryByText(zh['terminal.noOutput'])).toBeNull() - }) - - it('surfaces retention gaps and stream failures above the panel', () => { - const view: ObservedJob = { - jobId: 'bash-1' as JobView['id'], - text: 'tail only', - gapBefore: true, - streaming: false, - error: 'connection lost', - } - render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) - expect(screen.getByText(zh['output.gap'])).toBeDefined() - expect(screen.getByText('实时输出流中断:connection lost')).toBeDefined() - }) - - it('bridges Tab between the trigger and the portaled list and closes on Escape', () => { - render() - const trigger = screen.getAllByRole('button')[0]! - fireEvent.keyDown(trigger, { key: 'Tab' }) - openList() - const [first, last] = within(screen.getByRole('list', { name: zh['list.aria'] })).getAllByRole('button') - trigger.focus() - // Shift+Tab from the trigger leaves toward the controls before it. - expect(fireEvent.keyDown(trigger, { key: 'Tab', shiftKey: true })).toBe(true) - expect(document.activeElement).toBe(trigger) - // Tab from the trigger enters the list. - expect(fireEvent.keyDown(trigger, { key: 'Tab' })).toBe(false) - expect(document.activeElement).toBe(first) - // Inside the list Tab stays the browser's until an end is reached. - expect(fireEvent.keyDown(first!, { key: 'Tab' })).toBe(true) - // Tab off the last control resumes from the trigger's place in the page. - expect(fireEvent.keyDown(last!, { key: 'Tab' })).toBe(true) - expect(document.activeElement).toBe(trigger) - // Shift+Tab off the first control returns to the trigger itself. - first!.focus() - expect(fireEvent.keyDown(first!, { key: 'Tab', shiftKey: true })).toBe(false) - expect(document.activeElement).toBe(trigger) - first!.focus() - fireEvent.keyDown(first!, { key: 'Escape' }) - expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull() - expect(document.activeElement).toBe(trigger) - }) - - it('stops observation when the popover closes via Escape', () => { - const stop = vi.fn() - render( stop)} />) - openList() - fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) - fireEvent.keyDown(screen.getByRole('list', { name: zh['list.aria'] }), { key: 'Escape' }) - expect(stop).toHaveBeenCalledTimes(1) - expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull() - }) - - it('folds an expanded panel whose row left the roster', () => { - const stop = vi.fn() - // One stable observe identity across renders, as the inject face provides. - const observe = () => stop - const { rerender } = render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) - rerender() - expect(stop).toHaveBeenCalledTimes(1) - expect(screen.queryByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'other') })).toBeNull() - }) -}) - -describe('JobListAction human kill', () => { - const stopTitle = (label: string): string => zh['kill.stop'].replace('{label}', label) - - it('offers the stop control only on running rows', () => { - render() - openList() - expect(screen.getByTitle(stopTitle('pnpm run build'))).toBeDefined() - expect(screen.queryByTitle(stopTitle('done'))).toBeNull() - }) - - it('arms on the first press and kills on the confirming press', async () => { - const killJob = vi.fn(async () => true) - render() - openList() - const stop = screen.getByTitle(stopTitle('pnpm run build')) - fireEvent.click(stop) - expect(killJob).not.toHaveBeenCalled() - expect(stop.getAttribute('data-kill-state')).toBe('armed') - expect(screen.getByTitle(zh['kill.confirm'])).toBe(stop) - // The armed step is legible without hover: the button carries the label. - expect(stop.textContent).toBe(zh['kill.confirmAction']) - await act(async () => { fireEvent.click(stop) }) - expect(killJob).toHaveBeenCalledWith(SESSION, 'bash-1') - // An admitted kill stays pending: the unary response and the jobs frames - // have no cross-carrier ordering, so only the authoritative frame (the row - // leaving the killable set) releases the control — never the response. - expect(stop.getAttribute('data-kill-state')).toBe('pending') - expect(stop.hasAttribute('disabled')).toBe(true) - }) - - it('an armed press disarms after the confirmation window', () => { - vi.useFakeTimers() - const killJob = vi.fn(async () => true) - render() - openList() - const stop = screen.getByTitle(stopTitle('pnpm run build')) - fireEvent.click(stop) - expect(stop.getAttribute('data-kill-state')).toBe('armed') - act(() => { vi.advanceTimersByTime(3_000) }) - expect(stop.getAttribute('data-kill-state')).toBe('idle') - expect(killJob).not.toHaveBeenCalled() - }) - - it('a rejected kill shows its hint and then resets', async () => { - // Fake timers from the start so the failed-hint reset arms on the fake clock. - vi.useFakeTimers() - const killJob = vi.fn(async () => false) - render() - openList() - const stop = screen.getByTitle(stopTitle('pnpm run build')) - fireEvent.click(stop) - await act(async () => { fireEvent.click(stop) }) - expect(stop.getAttribute('data-kill-state')).toBe('failed') - expect(screen.getByTitle(zh['kill.failed'])).toBe(stop) - act(() => { vi.advanceTimersByTime(4_000) }) - expect(stop.getAttribute('data-kill-state')).toBe('idle') - }) - - it('arming a second row disarms the first', () => { - render() - openList() - const first = screen.getByTitle(stopTitle('pnpm run build')) - fireEvent.click(first) - expect(first.getAttribute('data-kill-state')).toBe('armed') - const second = screen.getByTitle(stopTitle('pnpm run watch')) - fireEvent.click(second) - expect(second.getAttribute('data-kill-state')).toBe('armed') - expect(first.getAttribute('data-kill-state')).toBe('idle') - }) - - it('a kill resolving after another row armed leaves the newer phase alone', async () => { - let resolveKill!: (ok: boolean) => void - const killJob = vi.fn(() => new Promise((resolve) => { resolveKill = resolve })) - render() - openList() - const first = screen.getByTitle(stopTitle('pnpm run build')) - fireEvent.click(first) - fireEvent.click(first) - expect(killJob).toHaveBeenCalledTimes(1) - // While the first kill is in flight, the user arms the second row; the - // late resolution must not clobber that newer phase. - const second = screen.getByTitle(stopTitle('pnpm run watch')) - fireEvent.click(second) - expect(second.getAttribute('data-kill-state')).toBe('armed') - await act(async () => { resolveKill(false) }) - expect(second.getAttribute('data-kill-state')).toBe('armed') - expect(first.getAttribute('data-kill-state')).toBe('idle') - }) - - it('clears an armed phase whose row stopped being killable', () => { - const { rerender } = render() - openList() - const stop = screen.getByTitle(stopTitle('pnpm run build')) - fireEvent.click(stop) - expect(stop.getAttribute('data-kill-state')).toBe('armed') - rerender() - // The stopping row offers no kill control any more, and the stale phase is gone. - expect(screen.queryByTitle(stopTitle('pnpm run build'))).toBeNull() - expect(document.querySelector('[data-kill-state]')).toBeNull() - }) -}) - -it.each([1, 2, 5, 21])('renders count-independent Russian labels for %i jobs', (count) => { - const jobs = Array.from({ length: count }, (_, i) => job({ id: `job-${i}` as JobView['id'] })) - const translate: JobListActionProps['t'] = makeTranslate(ru) - const view = render() - expect(screen.getByRole('button', { name: `Фоновые задачи: ${count}` })).toBeDefined() - view.rerender( ({ ...item, status: 'completed', finishedAt: 1_700_000_003_000 })))} t={translate} />) - expect(screen.getByRole('button', { name: `Фоновые задачи: ${count}` })).toBeDefined() -}) diff --git a/packages/client/ui-jobs/tests/jobs-section.client.spec.tsx b/packages/client/ui-jobs/tests/jobs-section.client.spec.tsx new file mode 100644 index 0000000000..296b28fc00 --- /dev/null +++ b/packages/client/ui-jobs/tests/jobs-section.client.spec.tsx @@ -0,0 +1,465 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { JobsSnapshot, JobView, ObservedJob } from '@deepseek-ai/dsh-api-job-controller/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { JobsSection, type JobsSectionProps } from '../src/client/JobsSection.tsx' +import { zh, ru } from '../src/client/locales.ts' + +beforeEach(() => { + class TooltipObserver implements ResizeObserver { + constructor(private readonly callback: ResizeObserverCallback) {} + observe(target: Element): void { + const size = { inlineSize: 160, blockSize: 30 } + this.callback([{ + target, borderBoxSize: [size], contentBoxSize: [size], devicePixelContentBoxSize: [size], contentRect: new DOMRect(), + }], this) + } + unobserve(): void {} + disconnect(): void {} + } + vi.stubGlobal('ResizeObserver', TooltipObserver) + vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true }))) +}) + +beforeEach(() => { + vi.stubGlobal('CSS', { supports: (property: string) => property === '-webkit-backdrop-filter' }) +}) + +afterEach(() => { + cleanup() + vi.restoreAllMocks() + vi.unstubAllGlobals() + vi.useRealTimers() +}) + +const SESSION = 'session' as SessionId +const t: JobsSectionProps['t'] = makeTranslate(zh) + +/** A running job with nothing retained yet. */ +function job(over: Partial = {}): JobView { + return { + id: 'bash-1' as JobView['id'], + kind: 'bash', + label: 'pnpm run build', + status: 'running', + startedAt: 1_700_000_000_000, + output: { total: 0, earliest: 0 }, + ...over, + } +} + +/** A job that left retained output behind, so its row offers a panel even once settled. */ +function outputJob(over: Partial = {}): JobView { + return job({ output: { total: 12, earliest: 0 }, ...over }) +} + +function props( + jobs: readonly JobView[], + observe: JobsSectionProps['observe'] = () => () => {}, + observed: Readonly> = {}, + killJob: JobsSectionProps['killJob'] = async () => true, + watchRows: JobsSectionProps['watchRows'] = () => () => {}, +): JobsSectionProps { + const jobsState: JobsSnapshot = { rows: jobs.length > 0 ? { [SESSION]: jobs } : {}, observed } + function useJobs(select: (value: JobsSnapshot) => T): T { + return select(jobsState) + } + return { sessionId: SESSION, useJobs, watchRows, observe, killJob, t } as JobsSectionProps +} + +/** The section renders its rows inline; there is no trigger to open. */ +function openList(): void {} + +describe('JobsSection visibility', () => { + it('renders nothing while the session sees no jobs', () => { + const { container } = render() + expect(container.innerHTML).toBe('') + }) + + it('watches the session roster while mounted and releases it on unmount', () => { + const stop = vi.fn() + const watchRows = vi.fn(() => stop) + const { unmount } = render() + expect(watchRows).toHaveBeenCalledWith(SESSION) + expect(stop).not.toHaveBeenCalled() + unmount() + expect(stop).toHaveBeenCalledTimes(1) + }) + +}) + +describe('JobsSection rows', () => { + it('renders a settled job without retained output as a static row', () => { + render() + expect(screen.getByRole('list', { name: zh['list.aria'] })).toBeDefined() + expect(screen.getByText('explore the repo')).toBeDefined() + expect(screen.queryByRole('button', { name: zh['row.expandAria'].replace('{label}', 'explore the repo') })).toBeNull() + }) + + it('offers a panel on a live row before any output arrived', () => { + render() + openList() + expect(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'warming up') })).toBeDefined() + }) + + it('shows the live progress line in place of the status word', () => { + render() + openList() + const list = screen.getByRole('list', { name: zh['list.aria'] }) + expect(within(list).getByText('pnpm run build')).toBeDefined() + expect(within(list).getByText('winding down')).toBeDefined() + }) + + it('folds the settled tail behind its count while live work exists, and clears on demand', () => { + const settled = [job({ id: 'bash-2' as JobView['id'], label: 'settled work', status: 'completed', finishedAt: 1_700_000_012_000 })] + render() + openList() + const toggle = screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') }) + // Folded by default while something runs; the toggle expands it. + expect(toggle.getAttribute('aria-expanded')).toBe('false') + expect(screen.queryByText('settled work')).toBeNull() + fireEvent.click(toggle) + expect(screen.getByText('settled work')).toBeDefined() + // Clearing hides the tail client-side and drops the whole section line. + fireEvent.click(screen.getByRole('button', { name: zh['section.clear'] })) + expect(screen.queryByText('settled work')).toBeNull() + expect(screen.queryByRole('button', { name: zh['section.clear'] })).toBeNull() + }) + + it('opens the settled tail by default when nothing is live', () => { + render() + openList() + expect(screen.getByText('pnpm run build')).toBeDefined() + expect(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') }).getAttribute('aria-expanded')).toBe('true') + }) + + it('clearing drops an expanded settled panel with its rows', () => { + const observe = vi.fn(() => () => {}) + render() + openList() + // Nothing live: the tail is open; expand the settled row's output panel. + fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'settled work') })) + expect(observe).toHaveBeenCalledWith(SESSION, 'bash-2') + fireEvent.click(screen.getByRole('button', { name: zh['section.clear'] })) + expect(screen.queryByText('settled work')).toBeNull() + expect(screen.queryByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'settled work') })).toBeNull() + }) + + it('shows a settled duration and ticks a live one', () => { + vi.useFakeTimers({ now: 1_700_000_020_000 }) + render() + openList() + fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '3') })) + expect(screen.getByText('5秒')).toBeDefined() + expect(screen.getByText('12秒')).toBeDefined() + expect(screen.getByText('1小时3分')).toBeDefined() + expect(screen.getByText('1分12秒')).toBeDefined() + act(() => { vi.advanceTimersByTime(1_000) }) + expect(screen.getByText('6秒')).toBeDefined() + }) + + it('lists rows with kind, label, and detail-or-status', () => { + render() + openList() + fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') })) + const list = screen.getByRole('list', { name: zh['list.aria'] }) + const items = within(list).getAllByRole('listitem') + // The section line is a listitem too now: live row, section, settled row. + expect(items).toHaveLength(3) + expect(items[0]?.textContent).toContain('pnpm run build') + // A live row's second line is kind · duration; the status word only + // appears through a detail (none while running). + expect(items[0]?.textContent).toMatch(/小时|分|秒/) + expect(items[2]?.textContent).toContain('exit code: 3') + }) + + it('orders live rows first by start and settled rows newest-first with tie-breaks', () => { + const settled = (id: string, label: string, startedAt: number, finishedAt?: number): JobView => + job({ + id: id as JobView['id'], + label, + status: 'completed', + startedAt, + ...finishedAt !== undefined ? { finishedAt } : {}, + }) + render() + openList() + fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '5') })) + const labels = within(screen.getByRole('list', { name: zh['list.aria'] })) + .getAllByRole('listitem') + .map(item => item.querySelector('[title]')?.getAttribute('title')) + .filter((title): title is string => title != null && !title.startsWith('已运行') && !title.startsWith('耗时')) + expect(labels).toEqual([ + 'live-2', 'live-1', 'settled-d', 'settled-a', 'settled-c', 'settled-b', 'settled-e', + ]) + expect(screen.getAllByText(zh['status.completed']).length).toBeGreaterThan(0) + }) + + it('breaks a settled tie on start order so map iteration never decides it', () => { + render() + openList() + expect(within(screen.getByRole('list')).getAllByRole('listitem').map(row => row.querySelector('[title]')?.getAttribute('title')).filter(title => title !== undefined)) + .toEqual(['first', 'second']) + }) + + it('prefers the producer detail over the generic status word', () => { + render() + openList() + expect(within(screen.getByRole('list')).getByText('signal: SIGTERM')).toBeDefined() + }) + + it('renders settled status words and every lifecycle indicator', () => { + render() + openList() + fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '3') })) + for (const word of ['已完成', '已取消', '已失败']) { + expect(within(screen.getByRole('list')).getByText(word)).toBeDefined() + } + expect([...screen.getByRole('list').querySelectorAll('li [data-state]')].map(node => node.getAttribute('data-state'))) + .toEqual(['ongoing', 'warning', 'done', 'warning', 'error']) + }) +}) + +describe('JobsSection observation', () => { + it('marks killed rows, renders every output line unfolded, and copies the command', async () => { + const writeText = vi.fn().mockResolvedValue(undefined) + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) + const lines = Array.from({ length: 24 }, (_value, index) => `line ${index + 1}`).join('\n') + const view: ObservedJob = { + jobId: 'bash-1' as JobView['id'], + text: lines, + gapBefore: false, + streaming: false, + } + render() + openList() + expect(screen.getByText(zh['status.killed'])).toBeDefined() + fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) + // The panel scrolls instead of folding: every line renders, no fold control. + expect(screen.getByText('line 1')).toBeDefined() + expect(screen.getByText('line 24')).toBeDefined() + expect(screen.queryByRole('button', { name: zh['terminal.expandAria'].replace('{n}', '8') })).toBeNull() + // The panel draws no state dot or label of its own — the row carries it. + expect(screen.queryByText(zh['terminal.done'])).toBeNull() + // The copy control carries the command, not the output. + await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['terminal.copy'] })) }) + expect(writeText).toHaveBeenCalledWith('pnpm run build') + }) + + it('starts observing on expand with the session identity, renders the live text, and stops on collapse', () => { + const stop = vi.fn() + const observe = vi.fn(() => stop) + const view: ObservedJob = { + jobId: 'bash-1' as JobView['id'], + text: 'compiling…\n', + gapBefore: false, + streaming: true, + } + render() + openList() + fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) + expect(observe).toHaveBeenCalledWith(SESSION, 'bash-1') + expect(screen.getByText('compiling…')).toBeDefined() + + fireEvent.click(screen.getByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'pnpm run build') })) + expect(stop).toHaveBeenCalledTimes(1) + }) + + it('renders a running panel with the prompt alone for a live row whose output has not arrived', () => { + const view: ObservedJob = { + jobId: 'bash-1' as JobView['id'], + text: '', + gapBefore: false, + streaming: true, + } + render() + openList() + fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) + expect(screen.getByRole('list', { name: zh['list.aria'] }).querySelector('[data-running]')).not.toBeNull() + expect(screen.queryByText(zh['terminal.noOutput'])).toBeNull() + }) + + it('surfaces retention gaps and stream failures above the panel', () => { + const view: ObservedJob = { + jobId: 'bash-1' as JobView['id'], + text: 'tail only', + gapBefore: true, + streaming: false, + error: 'connection lost', + } + render() + openList() + fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) + expect(screen.getByText(zh['output.gap'])).toBeDefined() + expect(screen.getByText('实时输出流中断:connection lost')).toBeDefined() + }) + + it('folds an expanded panel whose row left the roster', () => { + const stop = vi.fn() + // One stable observe identity across renders, as the inject face provides. + const observe = () => stop + const { rerender } = render() + openList() + fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) + rerender() + expect(stop).toHaveBeenCalledTimes(1) + expect(screen.queryByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'other') })).toBeNull() + }) +}) + +describe('JobsSection human kill', () => { + const stopTitle = (label: string): string => zh['kill.stop'].replace('{label}', label) + + it('offers the stop control only on running rows', () => { + render() + openList() + expect(screen.getByTitle(stopTitle('pnpm run build'))).toBeDefined() + expect(screen.queryByTitle(stopTitle('done'))).toBeNull() + }) + + it('arms on the first press and kills on the confirming press', async () => { + const killJob = vi.fn(async () => true) + render() + openList() + const stop = screen.getByTitle(stopTitle('pnpm run build')) + fireEvent.click(stop) + expect(killJob).not.toHaveBeenCalled() + expect(stop.getAttribute('data-kill-state')).toBe('armed') + expect(screen.getByTitle(zh['kill.confirm'])).toBe(stop) + // The armed step is legible without hover: the button carries the label. + expect(stop.textContent).toBe(zh['kill.confirmAction']) + await act(async () => { fireEvent.click(stop) }) + expect(killJob).toHaveBeenCalledWith(SESSION, 'bash-1') + // An admitted kill stays pending: the unary response and the jobs frames + // have no cross-carrier ordering, so only the authoritative frame (the row + // leaving the killable set) releases the control — never the response. + expect(stop.getAttribute('data-kill-state')).toBe('pending') + expect(stop.hasAttribute('disabled')).toBe(true) + }) + + it('an armed press disarms after the confirmation window', () => { + vi.useFakeTimers() + const killJob = vi.fn(async () => true) + render() + openList() + const stop = screen.getByTitle(stopTitle('pnpm run build')) + fireEvent.click(stop) + expect(stop.getAttribute('data-kill-state')).toBe('armed') + act(() => { vi.advanceTimersByTime(3_000) }) + expect(stop.getAttribute('data-kill-state')).toBe('idle') + expect(killJob).not.toHaveBeenCalled() + }) + + it('a rejected kill shows its hint and then resets', async () => { + // Fake timers from the start so the failed-hint reset arms on the fake clock. + vi.useFakeTimers() + const killJob = vi.fn(async () => false) + render() + openList() + const stop = screen.getByTitle(stopTitle('pnpm run build')) + fireEvent.click(stop) + await act(async () => { fireEvent.click(stop) }) + expect(stop.getAttribute('data-kill-state')).toBe('failed') + expect(screen.getByTitle(zh['kill.failed'])).toBe(stop) + act(() => { vi.advanceTimersByTime(4_000) }) + expect(stop.getAttribute('data-kill-state')).toBe('idle') + }) + + it('arming a second row disarms the first', () => { + render() + openList() + const first = screen.getByTitle(stopTitle('pnpm run build')) + fireEvent.click(first) + expect(first.getAttribute('data-kill-state')).toBe('armed') + const second = screen.getByTitle(stopTitle('pnpm run watch')) + fireEvent.click(second) + expect(second.getAttribute('data-kill-state')).toBe('armed') + expect(first.getAttribute('data-kill-state')).toBe('idle') + }) + + it('a kill resolving after another row armed leaves the newer phase alone', async () => { + let resolveKill!: (ok: boolean) => void + const killJob = vi.fn(() => new Promise((resolve) => { resolveKill = resolve })) + render() + openList() + const first = screen.getByTitle(stopTitle('pnpm run build')) + fireEvent.click(first) + fireEvent.click(first) + expect(killJob).toHaveBeenCalledTimes(1) + // While the first kill is in flight, the user arms the second row; the + // late resolution must not clobber that newer phase. + const second = screen.getByTitle(stopTitle('pnpm run watch')) + fireEvent.click(second) + expect(second.getAttribute('data-kill-state')).toBe('armed') + await act(async () => { resolveKill(false) }) + expect(second.getAttribute('data-kill-state')).toBe('armed') + expect(first.getAttribute('data-kill-state')).toBe('idle') + }) + + it('clears an armed phase whose row stopped being killable', () => { + const { rerender } = render() + openList() + const stop = screen.getByTitle(stopTitle('pnpm run build')) + fireEvent.click(stop) + expect(stop.getAttribute('data-kill-state')).toBe('armed') + rerender() + // The stopping row offers no kill control any more, and the stale phase is gone. + expect(screen.queryByTitle(stopTitle('pnpm run build'))).toBeNull() + expect(document.querySelector('[data-kill-state]')).toBeNull() + }) +}) + +it('renders the Russian settled-count copy', () => { + const translate: JobsSectionProps['t'] = makeTranslate(ru) + render() + expect(screen.getByRole('button', { name: ru['section.settledCount'].replace('{count}', '1') })).toBeDefined() +}) diff --git a/packages/client/ui-jobs/tsconfig.json b/packages/client/ui-jobs/tsconfig.json index f5e1825084..5b38ad1aae 100644 --- a/packages/client/ui-jobs/tsconfig.json +++ b/packages/client/ui-jobs/tsconfig.json @@ -8,21 +8,18 @@ "src" ], "references": [ + { + "path": "../../../vendor/cordis" + }, { "path": "../../api/job-controller/tsconfig.client.json" }, { "path": "../../api/session-controller/tsconfig.client.json" }, - { - "path": "../../../vendor/cordis" - }, { "path": "../locale/tsconfig.client.json" }, - { - "path": "../ui-conversation/tsconfig.client.json" - }, { "path": "../ui-primitives" }, @@ -32,6 +29,9 @@ { "path": "../ui-session" }, + { + "path": "../ui-session-panel" + }, { "path": "../ui-slots" } diff --git a/packages/client/ui-subagent/package.json b/packages/client/ui-subagent/package.json index ade2634518..614e462dc8 100644 --- a/packages/client/ui-subagent/package.json +++ b/packages/client/ui-subagent/package.json @@ -34,9 +34,10 @@ "@deepseek-ai/dsh-client-resources", "@deepseek-ai/dsh-client-ui-chat", "@deepseek-ai/dsh-client-ui-conversation", - "@deepseek-ai/dsh-client-ui-primitives", - "@deepseek-ai/dsh-client-ui-sidebar-right", "@deepseek-ai/dsh-client-ui-input-trigger", + "@deepseek-ai/dsh-client-ui-primitives", + "@deepseek-ai/dsh-client-ui-session-panel", + "@deepseek-ai/dsh-client-ui-sidebar-right", "@deepseek-ai/dsh-client-ui-workspace" ], "platform": "web" @@ -51,6 +52,10 @@ "@deepseek-ai/cordis": "workspace:~" }, "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-agent-team": "workspace:*", + "@deepseek-ai/dsh-api-session-controller": "workspace:*", + "@deepseek-ai/dsh-client-connection": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", "@deepseek-ai/dsh-client-resources": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", @@ -58,20 +63,17 @@ "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", "@deepseek-ai/dsh-client-ui-input-trigger": "workspace:*", "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", + "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", + "@deepseek-ai/dsh-client-ui-session": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-panel": "workspace:*", + "@deepseek-ai/dsh-client-ui-sidebar-right": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", + "@deepseek-ai/dsh-client-ui-workspace": "workspace:*", + "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-subagent": "workspace:*", "@deepseek-ai/dsh-token-meter": "workspace:*", - "@deepseek-ai/cordis": "workspace:~", "react": "^18.2.0", - "react-dom": "^18.2.0", - "@deepseek-ai/dsh-api-session-controller": "workspace:*", - "@deepseek-ai/dsh-client-connection": "workspace:*", - "@deepseek-ai/dsh-session": "workspace:*", - "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", - "@deepseek-ai/dsh-client-ui-sidebar-right": "workspace:*", - "@deepseek-ai/dsh-client-ui-session": "workspace:*", - "@deepseek-ai/dsh-client-ui-workspace": "workspace:*", - "@deepseek-ai/dsh-agent-team": "workspace:*" + "react-dom": "^18.2.0" }, "files": [ "locale/*.json", diff --git a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css b/packages/client/ui-subagent/src/client/SubagentCatalog.module.css similarity index 81% rename from packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css rename to packages/client/ui-subagent/src/client/SubagentCatalog.module.css index d3f58ad409..b1713aff5b 100644 --- a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css +++ b/packages/client/ui-subagent/src/client/SubagentCatalog.module.css @@ -11,7 +11,6 @@ margin-left: 6px; } -.trigger, .switcherTrigger { display: inline-flex; align-items: center; @@ -26,10 +25,6 @@ cursor: pointer; } -.trigger { - gap: 4px; -} - .switcherTrigger { gap: 4px; min-width: 0; @@ -57,25 +52,6 @@ flex: none; } -.activitySlot { - display: inline-flex; - flex: none; - align-items: center; - justify-content: center; - width: 14px; - height: 14px; -} - -.trigger:focus-visible { - color: var(--dsw-alias-label-primary); -} - -@media (hover: hover) { - .trigger:hover { - color: var(--dsw-alias-label-primary); - } -} - .switcherTrigger:focus-visible { color: var(--dsw-alias-label-primary); } @@ -100,55 +76,6 @@ transition: transform 120ms ease; } -.trigger .compactIcon { - display: none; -} - -/* The title-row container drops passive preset text at 540px; this action yields later. */ -@container (max-width: 460px) { - .trigger .compactIcon { - display: block; - } - - .trigger .textModeActivity { - display: none; - } - - .trigger .count { - display: none; - } - - .trigger { - box-sizing: border-box; - width: 28px; - height: 28px; - padding: 0; - justify-content: center; - color: var(--dsw-alias-label-secondary); - } - - .trigger .activitySlot, - .trigger .activitySlot > svg { - width: 15px; - height: 15px; - } - - .trigger:focus-visible { - color: var(--dsw-alias-label-secondary); - } - - .trigger:active { - background: var(--dsw-alias-interactive-bg-active); - } - - @media (hover: hover) { - .trigger:hover { - color: var(--dsw-alias-label-secondary); - background: var(--dsw-alias-interactive-bg-hover); - } - } -} - .menu { position: fixed; z-index: 100; @@ -193,40 +120,20 @@ } } -.sectionHeader { - display: flex; - align-items: flex-start; - gap: 7px; - padding: 4px 7px 8px; -} - -.sectionIcon { - display: grid; - flex: none; - place-items: center; - width: 14px; - height: 24px; - color: var(--dsw-alias-label-tertiary); -} - -.sectionTitle { - flex: none; - margin: 0; - color: var(--dsw-alias-label-primary); - font-size: 13px; - font-weight: 500; - line-height: 24px; -} - +/* Progress beside the Session panel section title, one line. */ .sectionProgress { - margin-inline-start: 4px; - flex: 1 1 auto; - min-width: 0; - padding-top: 2px; + overflow: hidden; color: var(--dsw-alias-label-tertiary); - font-size: 13px; - line-height: 20px; - overflow-wrap: anywhere; + font: var(--dsw-font-xxs-12); + text-overflow: ellipsis; + white-space: nowrap; +} + +/* The Session panel section supplies the inset and scrolling. */ +.sectionBody { + display: flex; + flex-direction: column; + min-width: 0; } .sectionEmpty { @@ -240,7 +147,8 @@ position: relative; min-width: 0; } -.menuBody > [role="tree"] > .node { +.menuBody > [role="tree"] > .node, +.sectionBody > [role="tree"] > .node { margin-left: -2px; } diff --git a/packages/client/ui-subagent/src/client/SubagentCatalog.tsx b/packages/client/ui-subagent/src/client/SubagentCatalog.tsx new file mode 100644 index 0000000000..98a35ed536 --- /dev/null +++ b/packages/client/ui-subagent/src/client/SubagentCatalog.tsx @@ -0,0 +1,559 @@ +/** Subagent catalog tree shared by the Session panel section and the breadcrumb switcher. */ +import { useEffect, useRef, useState, type KeyboardEvent, type MouseEvent } from 'react' +import type { + SessionListState, SessionProjectionMap, SessionProjectionSnapshot, SessionSummary, +} from '@deepseek-ai/dsh-api-session-controller/client' +import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client' +import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { + IconChevronRightOutlineRegular, IconRefreshOutlineRegular, IconCheckOutlineRegular, StateDot, Tooltip, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' +import type { NS } from './locales.ts' +import type {} from '@deepseek-ai/dsh-token-meter/client' +import css from './SubagentCatalog.module.css' + +/** One Session's direct subagents with their live activity. */ +export type SubagentCatalogSnapshot = Omit & { + state: 'loading' | 'ready' | 'migration-required' | 'error' + entries: (SessionProjectionMap['subagentCatalog'][number] & { activity: 'running' | 'inactive' })[] +} + +/** Catalogs of every Session whose projections the Client holds. */ +export type Catalogs = Readonly> + +/** Business actions supplied by the slot registrations. */ +export type SubagentCatalogInjected = { + openChild: (address: SubagentAddress) => void + openChildAside: (address: SubagentAddress) => void + refreshProjection: (parentSessionId: SessionId) => void +} + +interface CatalogRowsProps { + parentSessionId: SessionId + currentSessionId: SessionId | undefined + catalog: SubagentCatalogSnapshot + catalogs: Catalogs + summaries: Readonly> + expanded: ReadonlySet + level: number + openChild: (address: SubagentAddress) => void + openChildAside: (address: SubagentAddress) => void + refreshProjection: (parentSessionId: SessionId) => void + toggleBranch: (childSessionId: SessionId) => void + closeCatalog: () => void +} + +function treeItems(root: HTMLElement): HTMLElement[] { + return Array.from(root.querySelectorAll('[role="treeitem"]:not([aria-disabled="true"])')) +} + +/** Compact token count shared in shape with the conversation stats strip. */ +function formatTokens(value: number, t: TranslateNS): string { + const scaled = (next: number): string => next >= 100 + ? String(Math.round(next)) + : String(Math.round(next * 10) / 10) + if (value < 1_000) return String(value) + if (value < 1_000_000) return t('tokens.thousand', { value: scaled(value / 1_000) }) + return t('tokens.million', { value: scaled(value / 1_000_000) }) +} + +/** Sum the four disjoint durable provider-usage buckets. */ +function tokenTotal( + usage: SessionProjectionMap['tokenUsage'] | undefined, +): number | undefined { + return usage === undefined + ? undefined + : usage.uncachedInputTokens + usage.outputTokens + + usage.cacheReadTokens + usage.cacheWriteTokens +} + +/** Exact whole-second active-turn duration for one catalog row. */ +function activityDuration( + summary: SessionSummary | undefined, + activity: 'running' | 'inactive', + now: number, +): number | undefined { + if (summary === undefined) return undefined + const timing: SessionProjectionMap['subagentTiming'] | undefined + = summary.projectionValues?.subagentTiming + if (timing === undefined) return undefined + if (timing.active === undefined) return timing.settledMs + const end = activity === 'running' + ? now + : timing.active.through + return timing.settledMs + Math.max(0, end - timing.active.since) +} + +interface DurationParts { + seconds: number + minutes: number + hours: number + days: number + totalMinutes: number + totalHours: number +} + +function splitDuration(ms: number): DurationParts { + const totalSeconds = Math.floor(Math.max(0, ms) / 1_000) + const totalMinutes = Math.floor(totalSeconds / 60) + const totalHours = Math.floor(totalMinutes / 60) + return { + seconds: totalSeconds % 60, + minutes: totalMinutes % 60, + hours: totalHours % 24, + days: Math.floor(totalHours / 24), + totalMinutes, + totalHours, + } +} + +/** Format a duration with decreasing visual precision at larger scales. */ +function formatDuration(ms: number, t: TranslateNS): string { + const { seconds, minutes, hours, days, totalMinutes, totalHours } = splitDuration(ms) + if (days >= 365) { + const years = Math.floor(days / 365) + const months = Math.floor((days % 365) / 30) + return months === 0 + ? t('duration.years', { years }) + : t('duration.yearsMonths', { years, months }) + } + if (days >= 30) { + const months = Math.floor(days / 30) + const remainingDays = days % 30 + return remainingDays === 0 + ? t('duration.months', { months }) + : t('duration.monthsDays', { months, days: remainingDays }) + } + if (days > 0) { + return hours === 0 + ? t('duration.days', { days }) + : t('duration.daysHours', { days, hours }) + } + if (totalHours > 0) { + return t('duration.hours', { + hours: totalHours, + minutes: String(minutes).padStart(2, '0'), + seconds: String(seconds).padStart(2, '0'), + }) + } + if (totalMinutes > 0) { + return t('duration.minutes', { + minutes: totalMinutes, + seconds: String(seconds).padStart(2, '0'), + }) + } + return t('duration.seconds', { seconds }) +} + +/** Preserve exact whole seconds for hover and accessible naming. */ +function formatExactDuration(ms: number, t: TranslateNS): string { + const { seconds, minutes, hours, days } = splitDuration(ms) + return days === 0 + ? formatDuration(ms, t) + : t('duration.exactDays', { + days, + hours: String(hours).padStart(2, '0'), + minutes: String(minutes).padStart(2, '0'), + seconds: String(seconds).padStart(2, '0'), + }) +} + +/** Render catalog loading without inventing child membership. */ +function CatalogLoadingRows({ t }: { t: TranslateNS }) { + return
{t('loading.label')}
+} + +/** A child becomes a known leaf only after its own authoritative catalog loads empty. */ +function isKnownLeaf(catalog: SubagentCatalogSnapshot | undefined): boolean { + return catalog?.state === 'ready' && catalog.entries.length === 0 +} + +/** The agent name unique among the row's siblings, or the Session ID for entries recorded without one. */ +/** + * Name a catalog entry when it has no description. + * @param entry - catalog entry. + * @returns the entry's display name. + */ +export function entryName(entry: SubagentCatalogSnapshot['entries'][number]): string { + return entry.mode === 'continuable' || entry.mode === 'external' ? entry.name ?? entry.id : entry.id +} + +/** Only a local child's last closed, normally completed turn receives the completed marker. */ +function completedEntry(entry: SubagentCatalogSnapshot['entries'][number], summary: SessionSummary | undefined): boolean { + return entry.mode !== 'external' && entry.activity === 'inactive' + && summary?.projectionValues?.subagentTiming?.lastTurnCompleted === true +} + +/** Count direct catalog members without treating external or other inactive entries as completed. */ +function catalogProgress(entries: SubagentCatalogSnapshot['entries'], summaries: CatalogRowsProps['summaries'], t: TranslateNS): string { + let completed = 0 + let active = 0 + let inactive = 0 + let external = 0 + for (const entry of entries) { + if (entry.mode === 'external') external++ + else if (entry.activity === 'running') active++ + else if (completedEntry(entry, summaries[entry.id])) completed++ + else inactive++ + } + return [ + ...completed > 0 ? [t('progress.completed', { count: completed })] : [], + ...active > 0 ? [t('progress.active', { count: active })] : [], + ...inactive > 0 ? [t('progress.inactive', { count: inactive })] : [], + ...external > 0 ? [t('progress.external', { count: external })] : [], + ].join('\u2002·\u2002') +} + +/** Render one catalog level and recurse only through explicitly expanded rows. */ +function CatalogRows({ + parentSessionId, currentSessionId, catalog, catalogs, summaries, expanded, level, + openChild, openChildAside, refreshProjection, toggleBranch, closeCatalog, t, +}: CatalogRowsProps & { t: TranslateNS }) { + const [now, setNow] = useState(() => Date.now()) + const running = catalog.entries.some(entry => entry.activity === 'running') + useEffect(() => { + if (!running) return + const timer = setInterval(() => { setNow(Date.now()) }, 1_000) + return () => { clearInterval(timer) } + }, [running]) + const emptyLoading = catalog.state === 'loading' && catalog.entries.length === 0 + const reserveDisclosure = catalog.entries.some(entry => + entry.mode !== 'external' && !isKnownLeaf(catalogs[entry.id]) + && summaries[entry.id]?.formatStatus !== 'migration-required' + && catalogs[entry.id]?.state !== 'migration-required') + return ( + <> + {emptyLoading && ( + + )} + {catalog.state === 'error' && ( +
+ {catalog.error?.message ?? t('load.error')} + +
+ )} + {catalog.entries.map((entry) => { + const external = entry.mode === 'external' + const childCatalog = catalogs[entry.id] + const isCurrent = entry.id === currentSessionId + const knownLeaf = external || isKnownLeaf(childCatalog) + const requiresOpening = summaries[entry.id]?.formatStatus === 'migration-required' + || childCatalog?.state === 'migration-required' + const canExpand = !knownLeaf && !requiresOpening + const isExpanded = canExpand && expanded.has(entry.id) + const childLoading = childCatalog === undefined + || (childCatalog.state === 'loading' && childCatalog.entries.length === 0) + const summary = summaries[entry.id] + const description = entry.label || summary?.title + const name = entryName(entry) + const primaryLabel = description || name + const secondaryLabel = description ? name : undefined + const mode = external ? t('mode.external') : entry.mode === 'unknown' ? t('mode.unknown') + : entry.mode === 'one-shot' ? t('mode.oneShot') : t('mode.continuable') + const completed = completedEntry(entry, summary) + const activity = external ? undefined : entry.activity === 'running' + ? t('activity.running') + : completed + ? t('activity.completed') + : t('activity.inactive') + const secondary = [secondaryLabel, requiresOpening ? t('catalog.migrationRequired') : mode, activity] + .filter(value => value !== undefined) + .join(' · ') + const totalTokens = tokenTotal(summary?.projectionValues?.tokenUsage) + const durationMs = activityDuration( + summary, + entry.activity, + now, + ) + const tokenMetric = totalTokens === undefined + ? undefined + : t('tokens.total', { value: formatTokens(totalTokens, t) }) + const durationMetric = durationMs === undefined + ? undefined + : { + compact: formatDuration(durationMs, t), + exact: formatExactDuration(durationMs, t), + } + const metrics = [tokenMetric, durationMetric?.exact] + .filter(value => value !== undefined) + .join(' · ') + + const open = (): void => { + if (external) return + openChild({ + parentSessionId, + childSessionId: entry.id, + mode: entry.mode, + }) + closeCatalog() + } + const handleKey = (event: KeyboardEvent): void => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault() + event.stopPropagation() + open() + } else if ( + (event.key === 'ArrowRight' && canExpand && !isExpanded) + || (event.key === 'ArrowLeft' && isExpanded) + ) { + event.preventDefault() + event.stopPropagation() + toggleBranch(entry.id) + } + } + const toggle = (event: MouseEvent): void => { + event.preventDefault() + event.stopPropagation() + toggleBranch(entry.id) + } + + return ( +
+
value !== '').join(' ')} + {...canExpand ? { 'aria-expanded': isExpanded } : {}} + className={css.row} + onClick={open} + onKeyDown={handleKey} + > + {!canExpand + ? reserveDisclosure && + : ( + + )} +
+ + + + + {primaryLabel} + {secondaryLabel !== undefined && ( + {secondaryLabel} + )} + {requiresOpening && {t('catalog.migrationRequired')}} + + {metrics !== '' && ( + + {tokenMetric !== undefined && {tokenMetric}} + {durationMetric !== undefined && ( + + {durationMetric.compact} + + )} + + )} + {isCurrent + ? ( + + + + ) + : external ? : ( + + + + )} +
+
+ {isExpanded && ( +
+ {childCatalog === undefined + ? + : ( + + )} +
+ )} +
+ ) + })} + + ) +} + +/** + * Build every held Session's catalog from its projection and live status. + * @param projections - projection snapshots by Session. + * @param summaries - Session list rows by id. + * @param statuses - live Session statuses. + * @returns catalogs keyed by parent Session. + */ +export function deriveCatalogs( + projections: SessionListState['projectionsBySession'], + summaries: SessionListState['byId'], + statuses: SessionStatusSnapshot, +): Catalogs { + return Object.fromEntries(Object.entries(projections).map(([id, snapshot]) => { + const projected = snapshot.values.subagentCatalog + const state = snapshot.state === 'idle' + ? projected === undefined ? 'loading' : 'ready' + : snapshot.state === 'migration-required' && projected !== undefined ? 'ready' : snapshot.state + return [id, { + state, + error: snapshot.error, + entries: (projected ?? []).map(entry => ({ + ...entry, + activity: (statuses.get(entry.id)?.running ?? summaries[entry.id]?.running) === true + ? 'running' as const : 'inactive' as const, + })), + } satisfies SubagentCatalogSnapshot] + })) +} + +/** + * The direct subagents of `catalog`'s Session plus progress, as one phrase such as "2 of 3 done". + * @param catalog - catalog whose entries are counted. + * @param summaries - Session list rows by id. + * @param t - subagent copy. + * @returns the progress phrase, or an empty string without entries. + */ +export function progressOf(catalog: SubagentCatalogSnapshot, summaries: CatalogRowsProps['summaries'], t: TranslateNS): string { + return catalogProgress(catalog.entries, summaries, t) +} + +/** Props of one subagent tree. */ +export interface CatalogTreeProps { + /** Session whose direct catalog roots the tree. */ + rootSessionId: SessionId + /** Selected descendant highlighted in the tree. */ + currentSessionId?: SessionId | undefined + catalog: SubagentCatalogSnapshot + catalogs: Catalogs + summaries: CatalogRowsProps['summaries'] + openChild: (address: SubagentAddress) => void + openChildAside: (address: SubagentAddress) => void + refreshProjection: (parentSessionId: SessionId) => void + /** Called after a row opened a Session, so a surrounding popover or overlay can close. */ + onOpened: () => void + /** Focus the first row on mount, as a keyboard-opened popover does. */ + focusFirst?: boolean + t: TranslateNS +} + +/** + * Render a subagent tree with expandable branches and roving arrow-key focus. + * Expanding a branch refreshes that child's catalog; collapsing a branch also + * collapses its descendants. + * @param props - catalog data, actions, and copy. + * @returns the tree. + */ +export function CatalogTree({ + rootSessionId, currentSessionId, catalog, catalogs, summaries, + openChild, openChildAside, refreshProjection, onOpened, focusFirst = false, t, +}: CatalogTreeProps) { + const [expanded, setExpanded] = useState>(() => new Set()) + const treeRef = useRef(null) + useEffect(() => { + // Effects run after commit, when the tree element is attached. + if (focusFirst) treeItems(treeRef.current as HTMLDivElement)[0]?.focus() + }, [focusFirst]) + + const closeBranch = (root: SessionId): void => { + const closing = new Set() + const visit = (parentSessionId: SessionId): void => { + if (closing.has(parentSessionId) || !expanded.has(parentSessionId)) return + closing.add(parentSessionId) + for (const entry of catalogs[parentSessionId]?.entries ?? []) visit(entry.id) + } + visit(root) + setExpanded(current => new Set([...current].filter(id => !closing.has(id)))) + } + + const toggleBranch = (childSessionId: SessionId): void => { + if (expanded.has(childSessionId)) { + closeBranch(childSessionId) + return + } + setExpanded(current => new Set(current).add(childSessionId)) + refreshProjection(childSessionId) + } + + const navigate = (event: KeyboardEvent): void => { + const items = treeItems(event.currentTarget) + const index = items.indexOf(document.activeElement as HTMLElement) + const focusAt = (next: number): void => { items[(next + items.length) % items.length]?.focus() } + if (items.length === 0) return + if (event.key === 'Home') focusAt(0) + else if (event.key === 'End') focusAt(items.length - 1) + else if (event.key === 'ArrowDown') focusAt(index + 1) + else if (event.key === 'ArrowUp') focusAt(index < 0 ? items.length - 1 : index - 1) + else return + event.preventDefault() + } + + return ( +
+ +
+ ) +} diff --git a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx index 92a802ac66..2179934a72 100644 --- a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx +++ b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx @@ -1,180 +1,20 @@ -import { useMemo, useEffect, useId, useRef, useState, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react' +/** Breadcrumb switcher for subagent Sessions: the current title opens its siblings' tree. */ +import { useMemo, useEffect, useId, useRef, useState } from 'react' import { createPortal } from 'react-dom' -import { - type SessionProjectionMap, type SessionSummary, - type SessionProjectionSnapshot, -} from '@deepseek-ai/dsh-api-session-controller/client' -import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import { - IconChevronRightOutlineRegular, IconRefreshOutlineRegular, IconUsersOutlineRegular, - IconCheckOutlineRegular, MenuSurface, StateDot, Tooltip, -} from '@deepseek-ai/dsh-client-ui-primitives' -import type { HostObservable, InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' +import { MenuSurface } from '@deepseek-ai/dsh-client-ui-primitives' +import type { InjectFace, PropsLocale, PropsRuntime, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' import { NS } from './locales.ts' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' -import type {} from '@deepseek-ai/dsh-token-meter/client' -import type {} from '@deepseek-ai/dsh-agent-team/client' -import type {} from './slots.ts' -import css from './SubagentHeaderLineage.module.css' +import { CatalogTree, deriveCatalogs, entryName, type SubagentCatalogInjected, type SubagentCatalogSnapshot } from './SubagentCatalog.tsx' +import css from './SubagentCatalog.module.css' -type SubagentCatalogSnapshot = Omit & { - state: 'loading' | 'ready' | 'migration-required' | 'error' - entries: (SessionProjectionMap['subagentCatalog'][number] & { activity: 'running' | 'inactive' })[] -} -type Catalogs = Readonly> - -/** Business actions supplied by the slot registration. */ -export type SubagentCatalogInjected = { - openChild: (address: SubagentAddress) => void - openChildAside: (address: SubagentAddress) => void - refreshProjection: (parentSessionId: SessionId) => void -} - -/** Root catalog actions and availability of its optional footer. */ -export type SubagentCatalogActionInjected = SubagentCatalogInjected & { - hooks: { - /** Whether the catalog footer currently has a registered contributor. */ - footerAvailable: HostObservable - } -} +export type { SubagentCatalogInjected } from './SubagentCatalog.tsx' /** Full props for the session-header lineage renderer. */ export type SubagentHeaderLineageProps = PropsRuntime<'conversation.session.header.lineage'> & InjectFace & PropsLocale -interface CatalogRowsProps { - parentSessionId: SessionId - currentSessionId: SessionId | undefined - catalog: SubagentCatalogSnapshot - catalogs: Catalogs - summaries: Readonly> - expanded: ReadonlySet - level: number - openChild: (address: SubagentAddress) => void - openChildAside: (address: SubagentAddress) => void - refreshProjection: (parentSessionId: SessionId) => void - toggleBranch: (childSessionId: SessionId) => void - closeCatalog: () => void -} - -function treeItems(root: HTMLDivElement | null): HTMLElement[] { - return root === null - ? [] - : Array.from(root.querySelectorAll('[role="treeitem"]:not([aria-disabled="true"])')) -} - -/** Compact token count shared in shape with the conversation stats strip. */ -function formatTokens(value: number, t: TranslateNS): string { - const scaled = (next: number): string => next >= 100 - ? String(Math.round(next)) - : String(Math.round(next * 10) / 10) - if (value < 1_000) return String(value) - if (value < 1_000_000) return t('tokens.thousand', { value: scaled(value / 1_000) }) - return t('tokens.million', { value: scaled(value / 1_000_000) }) -} - -/** Sum the four disjoint durable provider-usage buckets. */ -function tokenTotal( - usage: SessionProjectionMap['tokenUsage'] | undefined, -): number | undefined { - return usage === undefined - ? undefined - : usage.uncachedInputTokens + usage.outputTokens - + usage.cacheReadTokens + usage.cacheWriteTokens -} - -/** Exact whole-second active-turn duration for one catalog row. */ -function activityDuration( - summary: SessionSummary | undefined, - activity: 'running' | 'inactive', - now: number, -): number | undefined { - if (summary === undefined) return undefined - const timing: SessionProjectionMap['subagentTiming'] | undefined - = summary.projectionValues?.subagentTiming - if (timing === undefined) return undefined - if (timing.active === undefined) return timing.settledMs - const end = activity === 'running' - ? now - : timing.active.through - return timing.settledMs + Math.max(0, end - timing.active.since) -} - -interface DurationParts { - seconds: number - minutes: number - hours: number - days: number - totalMinutes: number - totalHours: number -} - -function splitDuration(ms: number): DurationParts { - const totalSeconds = Math.floor(Math.max(0, ms) / 1_000) - const totalMinutes = Math.floor(totalSeconds / 60) - const totalHours = Math.floor(totalMinutes / 60) - return { - seconds: totalSeconds % 60, - minutes: totalMinutes % 60, - hours: totalHours % 24, - days: Math.floor(totalHours / 24), - totalMinutes, - totalHours, - } -} - -/** Format a duration with decreasing visual precision at larger scales. */ -function formatDuration(ms: number, t: TranslateNS): string { - const { seconds, minutes, hours, days, totalMinutes, totalHours } = splitDuration(ms) - if (days >= 365) { - const years = Math.floor(days / 365) - const months = Math.floor((days % 365) / 30) - return months === 0 - ? t('duration.years', { years }) - : t('duration.yearsMonths', { years, months }) - } - if (days >= 30) { - const months = Math.floor(days / 30) - const remainingDays = days % 30 - return remainingDays === 0 - ? t('duration.months', { months }) - : t('duration.monthsDays', { months, days: remainingDays }) - } - if (days > 0) { - return hours === 0 - ? t('duration.days', { days }) - : t('duration.daysHours', { days, hours }) - } - if (totalHours > 0) { - return t('duration.hours', { - hours: totalHours, - minutes: String(minutes).padStart(2, '0'), - seconds: String(seconds).padStart(2, '0'), - }) - } - if (totalMinutes > 0) { - return t('duration.minutes', { - minutes: totalMinutes, - seconds: String(seconds).padStart(2, '0'), - }) - } - return t('duration.seconds', { seconds }) -} - -/** Preserve exact whole seconds for hover and accessible naming. */ -function formatExactDuration(ms: number, t: TranslateNS): string { - const { seconds, minutes, hours, days } = splitDuration(ms) - return days === 0 - ? formatDuration(ms, t) - : t('duration.exactDays', { - days, - hours: String(hours).padStart(2, '0'), - minutes: String(minutes).padStart(2, '0'), - seconds: String(seconds).padStart(2, '0'), - }) -} - function SubagentSwitcherIcon() { return ( }) { - return
{t('loading.label')}
-} -/** A child becomes a known leaf only after its own authoritative catalog loads empty. */ -function isKnownLeaf(catalog: SubagentCatalogSnapshot | undefined): boolean { - return catalog?.state === 'ready' && catalog.entries.length === 0 -} - -/** The agent name unique among the row's siblings, or the Session ID for entries recorded without one. */ -function entryName(entry: SubagentCatalogSnapshot['entries'][number]): string { - return entry.mode === 'continuable' || entry.mode === 'external' ? entry.name ?? entry.id : entry.id -} - -/** Only a local child's last closed, normally completed turn receives the completed marker. */ -function completedEntry(entry: SubagentCatalogSnapshot['entries'][number], summary: SessionSummary | undefined): boolean { - return entry.mode !== 'external' && entry.activity === 'inactive' - && summary?.projectionValues?.subagentTiming?.lastTurnCompleted === true -} - -/** Count direct catalog members without treating external or other inactive entries as completed. */ -function catalogProgress(entries: SubagentCatalogSnapshot['entries'], summaries: CatalogRowsProps['summaries'], t: TranslateNS): string { - let completed = 0 - let active = 0 - let inactive = 0 - let external = 0 - for (const entry of entries) { - if (entry.mode === 'external') external++ - else if (entry.activity === 'running') active++ - else if (completedEntry(entry, summaries[entry.id])) completed++ - else inactive++ - } - return [ - ...completed > 0 ? [t('progress.completed', { count: completed })] : [], - ...active > 0 ? [t('progress.active', { count: active })] : [], - ...inactive > 0 ? [t('progress.inactive', { count: inactive })] : [], - ...external > 0 ? [t('progress.external', { count: external })] : [], - ].join('\u2002·\u2002') -} - -/** Render one catalog level and recurse only through explicitly expanded rows. */ -function CatalogRows({ - parentSessionId, currentSessionId, catalog, catalogs, summaries, expanded, level, - openChild, openChildAside, refreshProjection, toggleBranch, closeCatalog, t, -}: CatalogRowsProps & { t: TranslateNS }) { - const [now, setNow] = useState(() => Date.now()) - const running = catalog.entries.some(entry => entry.activity === 'running') - useEffect(() => { - if (!running) return - const timer = setInterval(() => { setNow(Date.now()) }, 1_000) - return () => { clearInterval(timer) } - }, [running]) - const emptyLoading = catalog.state === 'loading' && catalog.entries.length === 0 - const reserveDisclosure = catalog.entries.some(entry => - entry.mode !== 'external' && !isKnownLeaf(catalogs[entry.id]) - && summaries[entry.id]?.formatStatus !== 'migration-required' - && catalogs[entry.id]?.state !== 'migration-required') - return ( - <> - {emptyLoading && ( - - )} - {catalog.state === 'error' && ( -
- {catalog.error?.message ?? t('load.error')} - -
- )} - {catalog.entries.map((entry) => { - const external = entry.mode === 'external' - const childCatalog = catalogs[entry.id] - const isCurrent = entry.id === currentSessionId - const knownLeaf = external || isKnownLeaf(childCatalog) - const requiresOpening = summaries[entry.id]?.formatStatus === 'migration-required' - || childCatalog?.state === 'migration-required' - const canExpand = !knownLeaf && !requiresOpening - const isExpanded = canExpand && expanded.has(entry.id) - const childLoading = childCatalog === undefined - || (childCatalog.state === 'loading' && childCatalog.entries.length === 0) - const summary = summaries[entry.id] - const description = entry.label || summary?.title - const name = entryName(entry) - const primaryLabel = description || name - const secondaryLabel = description ? name : undefined - const mode = external ? t('mode.external') : entry.mode === 'unknown' ? t('mode.unknown') - : entry.mode === 'one-shot' ? t('mode.oneShot') : t('mode.continuable') - const completed = completedEntry(entry, summary) - const activity = external ? undefined : entry.activity === 'running' - ? t('activity.running') - : completed - ? t('activity.completed') - : t('activity.inactive') - const secondary = [secondaryLabel, requiresOpening ? t('catalog.migrationRequired') : mode, activity] - .filter(value => value !== undefined) - .join(' · ') - const totalTokens = tokenTotal(summary?.projectionValues?.tokenUsage) - const durationMs = activityDuration( - summary, - entry.activity, - now, - ) - const tokenMetric = totalTokens === undefined - ? undefined - : t('tokens.total', { value: formatTokens(totalTokens, t) }) - const durationMetric = durationMs === undefined - ? undefined - : { - compact: formatDuration(durationMs, t), - exact: formatExactDuration(durationMs, t), - } - const metrics = [tokenMetric, durationMetric?.exact] - .filter(value => value !== undefined) - .join(' · ') - - const open = (): void => { - if (external) return - openChild({ - parentSessionId, - childSessionId: entry.id, - mode: entry.mode, - }) - closeCatalog() - } - const handleKey = (event: KeyboardEvent): void => { - if (event.key === 'Enter' || event.key === ' ') { - event.preventDefault() - event.stopPropagation() - open() - } else if ( - (event.key === 'ArrowRight' && canExpand && !isExpanded) - || (event.key === 'ArrowLeft' && isExpanded) - ) { - event.preventDefault() - event.stopPropagation() - toggleBranch(entry.id) - } - } - const toggle = (event: MouseEvent): void => { - event.preventDefault() - event.stopPropagation() - toggleBranch(entry.id) - } - - return ( -
-
value !== '').join(' ')} - {...canExpand ? { 'aria-expanded': isExpanded } : {}} - className={css.row} - onClick={open} - onKeyDown={handleKey} - > - {!canExpand - ? reserveDisclosure && - : ( - - )} -
- - - - - {primaryLabel} - {secondaryLabel !== undefined && ( - {secondaryLabel} - )} - {requiresOpening && {t('catalog.migrationRequired')}} - - {metrics !== '' && ( - - {tokenMetric !== undefined && {tokenMetric}} - {durationMetric !== undefined && ( - - {durationMetric.compact} - - )} - - )} - {isCurrent - ? ( - - - - ) - : external ? : ( - - - - )} -
-
- {isExpanded && ( -
- {childCatalog === undefined - ? - : ( - - )} -
- )} -
- ) - })} - - ) -} - -interface CatalogDropdownSharedProps extends InjectFace { - /** Session whose direct catalog roots the tree. */ +interface SwitcherProps extends InjectFace { + /** Parent Session whose direct catalog roots the tree. */ rootSessionId: SessionId + /** Selected descendant highlighted in the tree. */ + currentSessionId: SessionId + /** Visible title included in the switcher's hover target. */ + displayTitle: string + /** Optional ancestor navigation when the combined title is clicked. */ + openTitle?: () => void useSessions: SubagentHeaderLineageProps['useSessions'] useSessionStatus: SubagentHeaderLineageProps['useSessionStatus'] t: TranslateNS - /** Section labels are useful only beside a visible shared-task list. */ - hasSharedTasks?: boolean - /** Retain an empty catalog's entry for shared tasks or a task-board error. */ - hasBoardContent?: boolean - renderFooter?: () => ReactNode } -type CatalogDropdownProps = CatalogDropdownSharedProps & ( - | { - /** Descendant-count control. */ - variant: 'count' - currentSessionId?: never - displayTitle?: never - openTitle?: never - } - | { - /** Current-title sibling switcher. */ - variant: 'switcher' - /** Selected descendant highlighted in the catalog. */ - currentSessionId: SessionId - /** Visible title included in the switcher's hover target. */ - displayTitle: string - /** Optional ancestor navigation when the combined title is clicked. */ - openTitle?: () => void - } -) - -/** One trigger-plus-tree dropdown over the catalog rooted at `rootSessionId`. */ -function CatalogDropdown(props: CatalogDropdownProps) { - const { - rootSessionId, currentSessionId, displayTitle, openTitle, variant, - useSessions, useSessionStatus, openChild, openChildAside, refreshProjection, t, hasSharedTasks = false, - } = props - const ancestorSwitcher = variant === 'switcher' && openTitle !== undefined +/** + * Title-and-chevron dropdown over the parent's subagent tree. Hover opens it + * after 150ms and leaving both surfaces closes it after 120ms; a click pins it + * until an outside press or Escape. With `openTitle`, a click navigates to the + * ancestor instead. + * @param props - tree root, current Session, title, Session hooks, actions, and copy. + * @returns the switcher. + */ +function Switcher({ + rootSessionId, currentSessionId, displayTitle, openTitle, + useSessions, useSessionStatus, openChild, openChildAside, refreshProjection, t, +}: SwitcherProps) { const projections = useSessions(state => state.projectionsBySession) const summaries = useSessions(state => state.byId) const statuses = useSessionStatus(value => value) - const catalogs = useMemo(() => { - return Object.fromEntries(Object.entries(projections).map(([id, snapshot]) => { - const projected = snapshot.values.subagentCatalog - const state = snapshot.state === 'idle' - ? projected === undefined ? 'loading' : 'ready' - : snapshot.state === 'migration-required' && projected !== undefined ? 'ready' : snapshot.state - return [id, { - state, - error: snapshot.error, - entries: (projected ?? []).map(entry => ({ - ...entry, - activity: (statuses.get(entry.id)?.running ?? summaries[entry.id]?.running) === true - ? 'running' as const : 'inactive' as const, - })), - } satisfies SubagentCatalogSnapshot] - })) - }, [projections, summaries, statuses]) - const catalog = catalogs[rootSessionId] - const [open, setOpen] = useState(false) - const [expanded, setExpanded] = useState>(() => new Set()) + const catalogs = useMemo(() => deriveCatalogs(projections, summaries, statuses), [projections, summaries, statuses]) + const catalog: SubagentCatalogSnapshot = catalogs[rootSessionId] ?? { entries: [], state: 'loading', error: null } + const [open, setOpen] = useState<'closed' | 'hover' | 'pinned' | 'keyboard'>('closed') const rootRef = useRef(null) const triggerRef = useRef(null) - const countRef = useRef(null) - const activityId = useId() const menuRef = useRef(null) - const anchorName = `--dsh-subagents-${activityId.replaceAll(':', '')}` - const hoverOpenTimer = useRef | undefined>(undefined) - const hoverCloseTimer = useRef | undefined>(undefined) - // A click-opened (pinned) menu ignores hover-out; only explicit dismissal closes it. - const pinnedRef = useRef(false) - const currentEntry = currentSessionId === undefined - ? undefined - : catalog?.entries.find(entry => entry.id === currentSessionId) - const switcherDisplayTitle = currentEntry !== undefined - ? currentEntry.label || entryName(currentEntry) - : displayTitle - const directChildren = catalog?.entries ?? [] - const directCount = directChildren.length - const runningCount = directChildren.filter(entry => entry.activity === 'running').length - const progress = catalogProgress(directChildren, summaries, t) - const totalCountKey = directCount === 1 ? 'count.total.one' : 'count.total.other' - const runningCountKey = runningCount === 1 ? 'count.running.one' : 'count.running.other' - const presentedCatalog: SubagentCatalogSnapshot | undefined = catalog ?? (variant === 'switcher' || props.hasBoardContent - ? { entries: [], state: 'loading', error: null } - : undefined) + const anchorName = `--dsh-subagents-${useId().replaceAll(':', '')}` + const hoverTimer = useRef | undefined>(undefined) + const currentEntry = catalog.entries.find(entry => entry.id === currentSessionId) + const title = currentEntry !== undefined ? currentEntry.label || entryName(currentEntry) : displayTitle + const shown = open !== 'closed' - const cancelHoverClose = (): void => { - if (hoverCloseTimer.current === undefined) return - clearTimeout(hoverCloseTimer.current) - hoverCloseTimer.current = undefined + const cancelHover = (): void => { + clearTimeout(hoverTimer.current) + hoverTimer.current = undefined } - - const cancelHoverOpen = (): void => { - if (hoverOpenTimer.current === undefined) return - clearTimeout(hoverOpenTimer.current) - hoverOpenTimer.current = undefined - } - - const changeOpen = (next: boolean, restoreFocus = false): void => { - cancelHoverOpen() - cancelHoverClose() - if (next) { - const trigger = triggerRef.current - /* v8 ignore next -- a queued callback can outlive the trigger */ - if (trigger === null) return - setOpen(true) - } - else { - pinnedRef.current = false - setOpen(false) - setExpanded(new Set()) - } + const close = (restoreFocus = false): void => { + cancelHover() + setOpen('closed') if (restoreFocus) queueMicrotask(() => { triggerRef.current?.focus() }) } - // CSS owns the header-width breakpoint; interaction reads its result only when scheduling hover. - const allowsHoverOpen = (): boolean => variant === 'switcher' - || (countRef.current !== null && getComputedStyle(countRef.current).display !== 'none') - - const scheduleHoverOpen = (): void => { - cancelHoverOpen() - cancelHoverClose() - if (open || !allowsHoverOpen()) return - hoverOpenTimer.current = setTimeout(() => { - hoverOpenTimer.current = undefined - if (allowsHoverOpen()) changeOpen(true) - }, 150) - } - - const scheduleHoverClose = (): void => { - cancelHoverOpen() - cancelHoverClose() - if (pinnedRef.current) return - hoverCloseTimer.current = setTimeout(() => { - hoverCloseTimer.current = undefined - changeOpen(false) - }, 120) - } - - const closeBranch = (root: SessionId): void => { - const closing = new Set() - const visit = (parentSessionId: SessionId): void => { - if (closing.has(parentSessionId) || !expanded.has(parentSessionId)) return - closing.add(parentSessionId) - const branch = catalogs[parentSessionId] - for (const entry of branch?.entries ?? []) { - visit(entry.id) - } - } - visit(root) - setExpanded(current => new Set([...current].filter(id => !closing.has(id)))) - } - - const toggleBranch = (childSessionId: SessionId): void => { - if (expanded.has(childSessionId)) { - closeBranch(childSessionId) - return - } - setExpanded(current => new Set(current).add(childSessionId)) - refreshProjection(childSessionId) - } - useEffect(() => { - if (!open) return + if (!shown) return const closeOutside = (event: PointerEvent): void => { - if ( - event.target instanceof Node - && !rootRef.current?.contains(event.target) - && !menuRef.current?.contains(event.target) - ) { - changeOpen(false) - } + if (event.target instanceof Node && !rootRef.current?.contains(event.target) && !menuRef.current?.contains(event.target)) close() } - document.addEventListener('pointerdown', closeOutside) const dismiss = (event: globalThis.KeyboardEvent): void => { if (event.key !== 'Escape') return event.preventDefault() - changeOpen(false, menuRef.current?.contains(document.activeElement) === true) + close(menuRef.current?.contains(document.activeElement) === true) } + document.addEventListener('pointerdown', closeOutside) document.addEventListener('keydown', dismiss) return () => { document.removeEventListener('pointerdown', closeOutside) document.removeEventListener('keydown', dismiss) } - }, [open]) + }, [shown]) + useEffect(() => cancelHover, []) - useEffect(() => () => { - cancelHoverOpen() - cancelHoverClose() - }, []) - - const visible = presentedCatalog !== undefined - && (variant === 'switcher' - || props.hasBoardContent || presentedCatalog.state === 'error' - || presentedCatalog.entries.length > 0) - useEffect(() => { - if (visible) return - cancelHoverOpen() - cancelHoverClose() - if (!open) return - pinnedRef.current = false - setOpen(false) - setExpanded(new Set()) - }, [visible, open]) - - if (!visible) return null - - const focusAt = (index: number): void => { - const items = treeItems(menuRef.current) - if (items.length === 0) return - items[(index + items.length) % items.length]?.focus() + const hoverIn = (pointerType: string): void => { + if (pointerType === 'touch') return + cancelHover() + if (shown) return + hoverTimer.current = setTimeout(() => { setOpen('hover') }, 150) } - - const navigate = (event: KeyboardEvent): void => { - if (event.target instanceof Element - && event.target !== triggerRef.current && event.target !== menuRef.current - && event.target.closest('[role="tree"]') === null) return - const items = treeItems(menuRef.current) - const index = items.indexOf(document.activeElement as HTMLElement) - if (event.key === 'Home') { - event.preventDefault() - focusAt(0) - } else if (event.key === 'End') { - event.preventDefault() - focusAt(items.length - 1) - } else if (event.key === 'ArrowDown') { - event.preventDefault() - focusAt(index + 1) - } else if (event.key === 'ArrowUp') { - event.preventDefault() - focusAt(index < 0 ? items.length - 1 : index - 1) - } + const hoverOut = (): void => { + cancelHover() + if (open !== 'hover') return + hoverTimer.current = setTimeout(() => { setOpen('closed') }, 120) } return ( -
- + - - {variant === 'count' && runningCount > 0 && ( - - )} - {open && createPortal(( + {title} + + + {shown && createPortal(( { - if (event.pointerType !== 'touch') cancelHoverClose() - }} - onPointerLeave={scheduleHoverClose} + onPointerEnter={(event) => { if (event.pointerType !== 'touch') cancelHover() }} + onPointerLeave={hoverOut} >
- {hasSharedTasks && ( -
- -

{t('section.title')}

- {progress && {progress}} -
- )} - {hasSharedTasks && presentedCatalog.state === 'ready' && directCount === 0 && ( -

{t('section.empty')}

- )} -
- { changeOpen(false) }} - t={t} - /> -
- {props.renderFooter?.()} + { close() }} + focusFirst={open === 'keyboard'} + t={t} + />
), document.body)} @@ -818,55 +184,9 @@ function CatalogDropdown(props: CatalogDropdownProps) { ) } -/** Full props for the root-session catalog entry in the header actions band. */ -export type SubagentCatalogActionProps = - PropsRuntime<'conversation.session.header.actions'> & InjectFace & PropsLocale - & Omit, 'SessionProvider'> - /** - * Session-header catalog action for root sessions: the descendant count and - * its dropdown after the preset label in the header actions band. Child sessions render nothing - * here — their breadcrumb switcher in the lineage slot owns the same - * navigation. - * @param props - Session standard props plus the catalog actions and translator. - * @returns The count dropdown, or null on a child session. - */ -export function SubagentCatalogAction(props: SubagentCatalogActionProps) { - const addressedChild = props.useSession(snapshot => snapshot.subagent !== null) - const listedChild = props.useSessions(state => state.byId[props.sessionId]?.origin === 'subagent') - if (addressedChild || listedChild) return null - return -} - -/** Bind task-board visibility only in root conversations. */ -function RootCatalogAction({ - sessionId, useProjection, useSessions, useSessionStatus, useFooterAvailable, - openChild, openChildAside, refreshProjection, t, renderSlot, -}: SubagentCatalogActionProps) { - const hasSharedTasks = useProjection('agentTeam', team => team?.enabled === true - && team.tasks.some(task => task.status !== 'deleted')) - const hasTaskFailure = useProjection('agentTeam', team => team?.enabled === true && team.failure !== undefined) - const footerAvailable = useFooterAvailable(value => value) - return ( - renderSlot('conversation.session.header.actions.subagent.footer', {})} - useSessions={useSessions} - useSessionStatus={useSessionStatus} - openChild={openChild} - openChildAside={openChildAside} - refreshProjection={refreshProjection} - t={t} - /> - ) -} - -/** - * Render one breadcrumb title together with its subagent navigation. + * Render one breadcrumb title together with its sibling switcher. The + * Session's own subagents are listed by the Session panel section. * @param props - Breadcrumb title, session standard props, and catalog actions. * @returns A title-and-chevron sibling switcher, or nothing on a root session. */ @@ -883,29 +203,20 @@ export function SubagentHeaderLineage({ const summary = state.byId[lineageSessionId] return summary?.origin === 'subagent' ? summary.parentId : undefined }) - const shared = { useSessions, useSessionStatus, openChild, openChildAside, refreshProjection, t } - // Root sessions carry no breadcrumb; their descendant count lives in the - // header actions band (SubagentCatalogAction). if (parentId === undefined) return null return ( - <> - - {openTitle === undefined && ( - - )} - + ) } diff --git a/packages/client/ui-subagent/src/client/SubagentsSection.tsx b/packages/client/ui-subagent/src/client/SubagentsSection.tsx new file mode 100644 index 0000000000..4c8eced002 --- /dev/null +++ b/packages/client/ui-subagent/src/client/SubagentsSection.tsx @@ -0,0 +1,94 @@ +/** Session panel section listing the current Session's subagents. */ +import { useMemo } from 'react' +import type { HostObservable, InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type { NS } from './locales.ts' +import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client' +import type {} from '@deepseek-ai/dsh-agent-team/client' +import { CatalogTree, deriveCatalogs, progressOf, type SubagentCatalogInjected, type SubagentCatalogSnapshot } from './SubagentCatalog.tsx' +import type {} from './slots.ts' +import css from './SubagentCatalog.module.css' + +/** Catalog actions and availability of the section's optional footer. */ +export type SubagentsSectionInjected = SubagentCatalogInjected & { + hooks: { + /** Whether the footer currently has a registered contributor. */ + footerAvailable: HostObservable + } +} + +/** Full props of the subagents section. */ +export type SubagentsSectionProps = + PropsRuntime<'conversation.session.panel.section'> + & Omit, 'SessionProvider'> + & InjectFace + & PropsLocale + +/** Full props of the section's progress title control. */ +export type SubagentsProgressProps = + PropsRuntime<'conversation.session.panel.section.actions'> & PropsLocale + +const LOADING: SubagentCatalogSnapshot = { entries: [], state: 'loading', error: null } + +/** + * Render the Session's subagent tree and, when a contributor registered one, + * the footer such as the shared task board. The section renders nothing while + * the Session has no subagents, no failed catalog read, and no board content. + * Opening a subagent closes the panel's overlay. + * @param props - Session hooks, panel owner values, catalog actions, footer renderer, and copy. + * @returns the section body, or null with nothing to show. + */ +export function SubagentsSection({ + sessionId, dismissOverlay, useSessions, useSessionStatus, useProjection, useFooterAvailable, + openChild, openChildAside, refreshProjection, renderSlot, t, +}: SubagentsSectionProps) { + const projections = useSessions(state => state.projectionsBySession) + const summaries = useSessions(state => state.byId) + const statuses = useSessionStatus(value => value) + const catalogs = useMemo(() => deriveCatalogs(projections, summaries, statuses), [projections, summaries, statuses]) + const footerAvailable = useFooterAvailable(value => value) + const hasSharedTasks = useProjection('agentTeam', team => team?.enabled === true + && team.tasks.some(task => task.status !== 'deleted')) + const hasTaskFailure = useProjection('agentTeam', team => team?.enabled === true && team.failure !== undefined) + const boardContent = footerAvailable && (hasSharedTasks || hasTaskFailure) + const catalog = catalogs[sessionId] + const listed = catalog !== undefined && (catalog.state === 'error' || catalog.entries.length > 0) + if (!listed && !boardContent) return null + const presented = catalog ?? LOADING + return ( +
+ {presented.state === 'ready' && presented.entries.length === 0 + ?

{t('section.empty')}

+ : ( + + )} + {footerAvailable && renderSlot('conversation.session.panel.subagents.footer', {})} +
+ ) +} + +/** + * Render the direct subagents' progress beside the section title. + * @param props - Session hooks and copy. + * @returns the progress phrase, or null without subagents. + */ +export function SubagentsProgress({ sessionId, useSessions, useSessionStatus, t }: SubagentsProgressProps) { + const projections = useSessions(state => state.projectionsBySession) + const summaries = useSessions(state => state.byId) + const statuses = useSessionStatus(value => value) + const progress = useMemo(() => { + const catalog = deriveCatalogs(projections, summaries, statuses)[sessionId] + return catalog === undefined ? '' : progressOf(catalog, summaries, t) + }, [projections, summaries, statuses, sessionId, t]) + if (progress === '') return null + return {progress} +} diff --git a/packages/client/ui-subagent/src/client/index.ts b/packages/client/ui-subagent/src/client/index.ts index a84992246d..ccb2f7bf05 100644 --- a/packages/client/ui-subagent/src/client/index.ts +++ b/packages/client/ui-subagent/src/client/index.ts @@ -3,7 +3,9 @@ import type { Context as ClientContext } from '@deepseek-ai/cordis' import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { ComposerChainProps } from '@deepseek-ai/dsh-client-ui-conversation/client' -import { SubagentCatalogAction, SubagentHeaderLineage, type SubagentCatalogInjected, type SubagentCatalogActionInjected } from './SubagentHeaderLineage.tsx' +import { SubagentHeaderLineage } from './SubagentHeaderLineage.tsx' +import type { SubagentCatalogInjected } from './SubagentCatalog.tsx' +import { SubagentsProgress, SubagentsSection, type SubagentsSectionInjected } from './SubagentsSection.tsx' import { SubagentReadOnlyComposer, type SubagentReadOnlyMatch, } from './SubagentReadOnlyComposer.tsx' @@ -12,6 +14,7 @@ import type {} from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-chat/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type {} from '@deepseek-ai/dsh-client-ui-session/client' +import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client' import type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type {} from '@deepseek-ai/dsh-client-ui-workspace/client' import { en, ja, es, fr, de, ru, pt, NS, zh, type SubagentKey } from './locales.ts' @@ -24,9 +27,9 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { } } -export type { - SubagentCatalogActionProps, SubagentCatalogInjected, SubagentCatalogActionInjected, SubagentHeaderLineageProps, -} from './SubagentHeaderLineage.tsx' +export type { SubagentCatalogInjected } from './SubagentCatalog.tsx' +export type { SubagentHeaderLineageProps } from './SubagentHeaderLineage.tsx' +export type { SubagentsProgressProps, SubagentsSectionInjected, SubagentsSectionProps } from './SubagentsSection.tsx' export type { SubagentReadOnlyComposerProps, SubagentReadOnlyMatch, } from './SubagentReadOnlyComposer.tsx' @@ -44,11 +47,13 @@ function selectReadOnlySubagent(owner: ComposerChainProps): SubagentReadOnlyMatc } /** - * Client plugin body: register the subagent catalog and read-only composer seats. + * Client plugin body: register the breadcrumb switcher, the Session panel + * subagents section, and the read-only composer. * @param ctx - client root context. */ export function apply(ctx: ClientContext): void { ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'ui-subagent: dictionaries') + const t = ctx.locale.bind(NS) ctx.inject(['resources', 'sidebarRightTabs'], (scope) => { registerSidebarChat(scope, ctx.locale.bind(NS)) }) @@ -67,8 +72,8 @@ export function apply(ctx: ClientContext): void { }, }) const footerAvailable = { - getSnapshot: () => ctx.slots.entries('conversation.session.header.actions.subagent.footer').length > 0, - subscribe: (listener: () => void) => ctx.slots.subscribe('conversation.session.header.actions.subagent.footer', listener), + getSnapshot: () => ctx.slots.entries('conversation.session.panel.subagents.footer').length > 0, + subscribe: (listener: () => void) => ctx.slots.subscribe('conversation.session.panel.subagents.footer', listener), } ctx.slots.inject( 'conversation.session.header.lineage', @@ -78,20 +83,25 @@ export function apply(ctx: ClientContext): void { inject: catalogActions, }, SubagentHeaderLineage), ) - ctx.slots.inject( - 'conversation.session.header.actions', - () => ctx.slots.register({ - name: 'conversation.session.header.actions', - id: 'subagent-catalog', - // Between the preset label (-10) and background tasks (20). - order: 10, + ctx.slots.inject('conversation.session.panel.section', function* () { + yield ctx.slots.register({ + name: 'conversation.session.panel.section', + id: 'subagents', + // After change requests (100), before background jobs (300). + order: 200, + label: () => t('section.title'), locale: NS, - inject: (sessionId): SubagentCatalogActionInjected => ({ + inject: (sessionId): SubagentsSectionInjected => ({ ...catalogActions(sessionId), hooks: { footerAvailable }, }), - children: { 'conversation.session.header.actions.subagent.footer': { kind: 'list', scope: 'session' } }, - }, SubagentCatalogAction), - ) + children: { 'conversation.session.panel.subagents.footer': { kind: 'list', scope: 'session' } }, + }, SubagentsSection) + yield ctx.slots.register({ + name: 'conversation.session.panel.section.actions', + key: 'subagents', + locale: NS, + }, SubagentsProgress) + }) ctx.slots.inject( 'conversation.composer', () => ctx.slots.register({ diff --git a/packages/client/ui-subagent/src/client/locales.ts b/packages/client/ui-subagent/src/client/locales.ts index 27a5b61391..6e87f7eef9 100644 --- a/packages/client/ui-subagent/src/client/locales.ts +++ b/packages/client/ui-subagent/src/client/locales.ts @@ -39,10 +39,6 @@ export const zh = { 'activity.inactive': '当前未运行', 'branch.collapse': '收起 {label} 的下级子智能体', 'branch.expand': '展开 {label} 的下级子智能体', - 'count.total.one': '{count} 个子智能体', - 'count.total.other': '{count} 个子智能体', - 'count.running.one': '{count} 个子智能体,正在运行', - 'count.running.other': '{count} 个子智能体,正在运行', 'switcher.aria': '切换子智能体:{title}', 'tree.aria': '子智能体会话', 'open.sidebar': '在侧边栏打开', @@ -90,10 +86,6 @@ export const en: Record = { 'activity.inactive': 'not running', 'branch.collapse': 'Collapse {label} descendants', 'branch.expand': 'Expand {label} descendants', - 'count.total.one': '{count} subagent', - 'count.total.other': '{count} subagents', - 'count.running.one': '{count} subagent running', - 'count.running.other': '{count} subagents running', 'switcher.aria': 'Switch subagent: {title}', 'tree.aria': 'Subagent sessions', 'open.sidebar': 'Open in sidebar', @@ -144,10 +136,6 @@ export const ja = { 'activity.inactive': '停止中', 'branch.collapse': '{label}の子孫を折りたたむ', 'branch.expand': '{label}の子孫を展開', - 'count.total.one': 'サブエージェント{count}件', - 'count.total.other': 'サブエージェント{count}件', - 'count.running.one': '実行中のサブエージェント{count}件', - 'count.running.other': '実行中のサブエージェント{count}件', 'switcher.aria': 'サブエージェントを切り替え: {title}', 'tree.aria': 'サブエージェントセッション', 'open.sidebar': 'サイドバーで開く', @@ -195,10 +183,6 @@ export const es = { 'activity.inactive': 'no corriendo', 'branch.collapse': 'Contraer descendientes de {label}', 'branch.expand': 'Ampliar descendientes de {label}', - 'count.total.one': 'Subagente {count}', - 'count.total.other': 'Subagentes {count}', - 'count.running.one': 'Subagente {count} ejecutándose', - 'count.running.other': 'Subagentes {count} ejecutándose', 'switcher.aria': 'Cambiar subagente: {title}', 'tree.aria': 'Sesiones de subagente', 'open.sidebar': 'Abrir en la barra lateral', @@ -246,10 +230,6 @@ export const fr = { 'activity.inactive': 'ne fonctionne pas', 'branch.collapse': 'Réduire les descendants de {label}', 'branch.expand': 'Développer les descendants de {label}', - 'count.total.one': 'Sous-agent {count}', - 'count.total.other': 'Sous-agents {count}', - 'count.running.one': "Sous-agent {count} en cours d'exécution", - 'count.running.other': "Sous-agents {count} en cours d'exécution", 'switcher.aria': 'Changer de sous-agent : {title}', 'tree.aria': 'Sessions de sous-agents', 'open.sidebar': 'Ouvrir dans la barre latérale', @@ -297,10 +277,6 @@ export const de = { 'activity.inactive': 'läuft nicht', 'branch.collapse': '{label}-Nachkommen reduzieren', 'branch.expand': 'Erweitern Sie {label}-Nachkommen', - 'count.total.one': '{count}-Subagent', - 'count.total.other': '{count}-Subagenten', - 'count.running.one': '{count}-Subagent läuft', - 'count.running.other': '{count} Subagenten laufen', 'switcher.aria': 'Subagent wechseln: {title}', 'tree.aria': 'Subagentensitzungen', 'open.sidebar': 'In der Seitenleiste öffnen', @@ -348,10 +324,6 @@ export const ru = { 'activity.inactive': 'не работает', 'branch.collapse': 'Свернуть потомков {label}', 'branch.expand': 'Развернуть потомков {label}', - 'count.total.one': 'Субагент {count}', - 'count.total.other': 'Субагенты {count}', - 'count.running.one': 'Субагент {count} работает', - 'count.running.other': 'Субагенты {count} работают', 'switcher.aria': 'Переключить субагент: {title}', 'tree.aria': 'Сеансы субагента', 'open.sidebar': 'Открыть в боковой панели', @@ -399,10 +371,6 @@ export const pt = { 'activity.inactive': 'não está funcionando', 'branch.collapse': 'Recolher {label} descendentes', 'branch.expand': 'Expandir {label} descendentes', - 'count.total.one': '{count} subagente', - 'count.total.other': '{count} subagentes', - 'count.running.one': '{count} subagente em execução', - 'count.running.other': '{count} subagentes em execução', 'switcher.aria': 'Alternar subagente: {title}', 'tree.aria': 'Sessões de subagente', 'open.sidebar': 'Abrir na barra lateral', diff --git a/packages/client/ui-subagent/src/client/slots.ts b/packages/client/ui-subagent/src/client/slots.ts index a3e379e62f..2233130f87 100644 --- a/packages/client/ui-subagent/src/client/slots.ts +++ b/packages/client/ui-subagent/src/client/slots.ts @@ -1,9 +1,10 @@ -/** Extension position below the root conversation's subagent catalog. */ +/** Extension position below the Session panel's subagent tree. */ +import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client' declare module '@deepseek-ai/dsh-client-ui-slots' { interface SlotMap { - /** Content below the root Session's subagent tree. */ - 'conversation.session.header.actions.subagent.footer': { + /** Content below the Session's subagent tree in the Session panel, such as the shared task board. */ + 'conversation.session.panel.subagents.footer': { kind: 'list' scope: 'session' } diff --git a/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts b/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts index b5006a277b..a0dd3c56cd 100644 --- a/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts @@ -11,9 +11,11 @@ import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { ComposerChainProps } from '@deepseek-ai/dsh-client-ui-conversation/client' import { apply as applyLocale, inject as localeInject } from '@deepseek-ai/dsh-client-locale/client' -import { - SubagentHeaderLineage, type SubagentCatalogInjected, type SubagentCatalogActionInjected, -} from '../src/client/SubagentHeaderLineage.tsx' +import { SubagentHeaderLineage } from '../src/client/SubagentHeaderLineage.tsx' +import type { SubagentCatalogInjected } from '../src/client/SubagentCatalog.tsx' +import type { SubagentsSectionInjected } from '../src/client/SubagentsSection.tsx' +import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' +import { en } from '../src/client/locales.ts' import { SubagentReadOnlyComposer, type SubagentReadOnlyMatch, } from '../src/client/SubagentReadOnlyComposer.tsx' @@ -64,7 +66,8 @@ async function provideSlotFaces(ctx: Context): Promise { name: 'root', children: { 'conversation.session.header.lineage': { kind: 'single', scope: 'session' }, - 'conversation.session.header.actions': { kind: 'list', scope: 'session' }, + 'conversation.session.panel.section': { kind: 'list', scope: 'session' }, + 'conversation.session.panel.section.actions': { kind: 'keyed', scope: 'session' }, 'conversation.composer': { kind: 'chain', scope: 'session' }, }, } as never, () => null) @@ -111,14 +114,14 @@ describe('apply', () => { it('keeps the root catalog extension available when optional Sidebar services arrive', async () => { const { ctx } = await fullBench(FAMILY) onTestFinished(() => ctx.fiber.dispose()) - ctx.slots.register({ name: 'conversation.session.header.actions.subagent.footer', id: 'test-content' }, () => null) + ctx.slots.register({ name: 'conversation.session.panel.subagents.footer', id: 'test-content' }, () => null) const registerResource = vi.fn(() => () => {}) const registerTab = vi.fn(() => () => {}) ctx.provide('resources', { register: registerResource } as never) ctx.provide('sidebarRightTabs', { register: registerTab } as never) await vi.waitFor(() => { expect(registerResource).toHaveBeenCalledOnce() }) expect(registerTab).toHaveBeenCalledOnce() - expect(ctx.slots.entries('conversation.session.header.actions.subagent.footer')).toHaveLength(1) + expect(ctx.slots.entries('conversation.session.panel.subagents.footer')).toHaveLength(1) }) it('registers catalog actions and selects read-only subagent composers from session facts', async () => { @@ -146,19 +149,21 @@ describe('apply', () => { { method: 'refreshProjections', args: [sid('parent')] }, ]) - // The root-session catalog seat registers in the actions band with the - // same business face, between the preset label (-10) and background - // tasks (20). - const actionEntry = ctx.slots.entries('conversation.session.header.actions') - .find(entry => entry.options.id === 'subagent-catalog')! - expect(actionEntry.options.order).toBe(10) - const actionProps = (actionEntry.inject as (id: SessionId) => SubagentCatalogActionInjected)(sid('parent')) - const source = actionProps.hooks.footerAvailable + // The Session panel section registers with the same business face, + // after change requests (100) and before background jobs (300), together + // with its progress control beside the title. + const sectionEntry = ctx.slots.entries('conversation.session.panel.section') + .find(entry => entry.options.id === 'subagents')! + expect(sectionEntry.options.order).toBe(200) + expect(resolveSlotLabel(sectionEntry.options.label)).toBe(en['section.title']) + expect(ctx.slots.entries('conversation.session.panel.section.actions').map(entry => entry.options.key)).toEqual(['subagents']) + const sectionProps = (sectionEntry.inject as (id: SessionId) => SubagentsSectionInjected)(sid('parent')) + const source = sectionProps.hooks.footerAvailable const changed = vi.fn() const unsubscribe = source.subscribe(changed) expect(source.getSnapshot()).toBe(false) const remove = ctx.slots.register({ - name: 'conversation.session.header.actions.subagent.footer', id: 'test-footer', + name: 'conversation.session.panel.subagents.footer', id: 'test-footer', }, () => null) expect(source.getSnapshot()).toBe(true) await vi.waitFor(() => { expect(changed).toHaveBeenCalledOnce() }) diff --git a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx index 43d2255936..3b39f187f0 100644 --- a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx +++ b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx @@ -10,10 +10,8 @@ import type { SubagentAddress, SubagentCatalogEntry } from '@deepseek-ai/dsh-sub import type { TeamProjection, TeamTaskId, TeamTaskView } from '@deepseek-ai/dsh-agent-team/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client' -import { - SubagentCatalogAction, SubagentHeaderLineage, - type SubagentCatalogActionProps, type SubagentHeaderLineageProps, -} from '../src/client/SubagentHeaderLineage.tsx' +import { SubagentHeaderLineage, type SubagentHeaderLineageProps } from '../src/client/SubagentHeaderLineage.tsx' +import { SubagentsProgress, SubagentsSection, type SubagentsProgressProps, type SubagentsSectionProps } from '../src/client/SubagentsSection.tsx' import { SubagentReadOnlyComposer } from '../src/client/SubagentReadOnlyComposer.tsx' import { en, zh } from '../src/client/locales.ts' @@ -30,7 +28,8 @@ const GRANDCHILD = 'grandchild' as SessionId const t: SubagentHeaderLineageProps['t'] = makeTranslate(zh) type HeaderCatalogProps = SubagentHeaderLineageProps - & Pick + & Pick + & { dismissOverlay?: () => void } type CatalogFixtureEntry = Entry extends SubagentCatalogEntry ? Omit & { activity: 'running' | 'inactive' } @@ -183,87 +182,25 @@ function enableTooltips(): void { } /** - * Both header seats as the real header composes them: the breadcrumb switcher - * (child sessions, lineage slot) and the actions-band catalog entry (root - * sessions) — exactly one renders per form. The actions seat sees the same - * session the lineage renders. + * The two surfaces as the real page composes them: the breadcrumb switcher + * (child sessions, lineage slot) and the Session panel section listing the + * Session's own subagents. The section sees the same Session the lineage renders. */ function HeaderCatalog(props: HeaderCatalogProps) { - const actionProps: SubagentCatalogActionProps = { - ...props, sessionId: props.lineageSessionId, + const sectionProps: SubagentsSectionProps = { + ...props, sessionId: props.lineageSessionId, presentation: 'docked', dismissOverlay: props.dismissOverlay ?? vi.fn(), useProjection: ((_key: 'agentTeam', selector: (value: TeamProjection | undefined) => boolean) => - props.useSessions(state => selector(state.projectionsBySession[props.lineageSessionId]?.values.agentTeam))) as SubagentCatalogActionProps['useProjection'], + props.useSessions(state => selector(state.projectionsBySession[props.lineageSessionId]?.values.agentTeam))) as SubagentsSectionProps['useProjection'], } return ( <> - + ) } describe('SubagentHeaderLineage', () => { - it.each([ - { dictionary: zh, total: '2 个子智能体', running: '1 个子智能体,正在运行' }, - { dictionary: en, total: '2 subagents', running: '1 subagent running' }, - ])('keeps the total accessible name separate from the running description: $total', ({ dictionary, total, running }) => { - const input = props(catalog()) - const view = render() - const trigger = screen.getByRole('button', { name: total }) - expect(trigger.textContent).toBe(total) - expect(document.getElementById(trigger.getAttribute('aria-describedby')!)?.textContent).toBe(running) - view.rerender() - expect(screen.getByRole('button', { name: total }).getAttribute('aria-describedby')).toBeNull() - }) - - it('shows a non-collapsible heading with direct-member progress beside shared tasks', () => { - const finished = 'finished' as SessionId - const paused = 'paused' as SessionId - const external = 'external' as SessionId - const entries: CatalogFixture['entries'] = [ - { id: CHILD, mode: 'continuable', label: 'worker', activity: 'running' }, - { id: finished, mode: 'continuable', label: 'finished', activity: 'inactive' }, - { id: paused, mode: 'continuable', label: 'paused', activity: 'inactive' }, - { id: external, mode: 'external', label: 'external', activity: 'running' }, - ] - const summaries: Record = { - [CHILD]: { ...summary(CHILD, 1), running: true, projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: true } } }, - [finished]: { ...summary(finished, 1), projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: true } } }, - [paused]: { ...summary(paused, 1), projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: false } } }, - [external]: { - ...summary(external, 1), running: true, projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: true } }, - }, - } - const input = props(catalog({ entries, team: sharedTeam }), { - [CHILD]: catalog({ entries: [{ id: GRANDCHILD, mode: 'continuable', label: 'nested', activity: 'running' }] }), - }, summaries) - const view = render() - fireEvent.click(screen.getByRole('button', { name: '4 个子智能体' })) - const header = view.container.ownerDocument.querySelector('[data-subagent-section-header]')! - expect(within(header).getByRole('heading', { name: '子智能体' })).toBeTruthy() - expect(within(header).queryByRole('button')).toBeNull() - expect(header.textContent).toBe('子智能体1 已完成\u2002·\u20021 进行中\u2002·\u20021 未运行\u2002·\u20021 外部任务') - fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) - expect(header.textContent).toContain('1 进行中') - expect(header.textContent).not.toContain('2 进行中') - view.rerender() - expect(header.textContent).toBe('Subagents1 completed\u2002·\u20021 in progress\u2002·\u20021 not running\u2002·\u20021 external') - }) - - it('omits zero progress counts from a completed-only catalog header', () => { - const input = props(catalog({ - team: sharedTeam, entries: [{ id: CHILD, mode: 'continuable', label: 'finished', activity: 'inactive' }], - }), {}, { - [CHILD]: { ...summary(CHILD, 1), projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: true } } }, - }) - render() - fireEvent.click(screen.getByRole('button', { name: '1 个子智能体' })) - const header = document.querySelector('[data-subagent-section-header]')! - expect(header.textContent).toBe('子智能体1 已完成') - }) it.each([ { name: 'absent Team projection', team: undefined, footer: true }, @@ -276,7 +213,6 @@ describe('SubagentHeaderLineage', () => { 'omits section headings from a members-only catalog with $name', ({ team, footer }) => { const input = props(catalog({ ...team === undefined ? {} : { team } })) render( select(footer)} />) - fireEvent.click(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) expect(screen.getByRole('tree')).toBeTruthy() expect(screen.queryByRole('heading')).toBeNull() expect(document.querySelector('[data-subagent-section-header]')).toBeNull() @@ -284,33 +220,11 @@ describe('SubagentHeaderLineage', () => { }, ) - it('shows the description above the Session id and opens the row without a description toggle', () => { - const description = 'Check the construction and all bounds. '.repeat(20).trim() - const input = props(catalog({ - entries: [{ id: CHILD, mode: 'continuable', label: description, activity: 'running' }], - })) - render() - fireEvent.click(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) - const row = screen.getByRole('treeitem', { name: new RegExp(CHILD) }) - const primary = within(row).getByText(description) - const id = within(row).getByText(CHILD) - expect(primary.compareDocumentPosition(id) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() - expect(row.getAttribute('aria-label')).toMatch(/^Check the construction/) - expect(primary.tagName).toBe('SPAN') - expect(primary.getAttribute('aria-expanded')).toBeNull() - expect(primary.querySelector('svg')).toBeNull() - expect(within(row).queryByRole('button', { name: /描述/ })).toBeNull() - fireEvent.click(primary) - expect(input.openChild).toHaveBeenCalledExactlyOnceWith({ parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' }) - expect(screen.queryByRole('treeitem')).toBeNull() - }) - it.each([undefined, ''])('keeps a single ID line when the creation description is %s', (label) => { const input = props(catalog({ entries: [{ id: CHILD, mode: 'one-shot', ...label === undefined ? {} : { label }, activity: 'running' }], }), {}, { [CHILD]: { ...summary(CHILD, 1), running: true } }) render() - fireEvent.click(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) const row = screen.getByRole('treeitem', { name: new RegExp(CHILD) }) expect(within(row).getAllByText(CHILD)).toHaveLength(1) expect(row.getAttribute('aria-label')).toMatch(new RegExp(`^${CHILD}`)) @@ -326,7 +240,6 @@ describe('SubagentHeaderLineage', () => { ], }), {}, { [CHILD]: { ...summary(CHILD, 1), running: true } }) render() - fireEvent.click(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) const named = screen.getByRole('treeitem', { name: /^Review the diff reviewer/ }) expect(within(named).getByText('Review the diff').compareDocumentPosition(within(named).getByText('reviewer')) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() @@ -339,87 +252,11 @@ describe('SubagentHeaderLineage', () => { expect(input.openChild).toHaveBeenCalledExactlyOnceWith({ parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' }) }) - it('hides an empty Team entry but keeps shared tasks and errors reachable without children', () => { - const input = props(catalog({ entries: [] })) - const initial = input.useSessions(state => state) - const mode: { enabled: boolean; tasks: TeamTaskView[]; failure?: string } = { enabled: true, tasks: [] } - const values = { ...initial.projectionsBySession[PARENT]!.values, agentTeam: mode } - const current = { - ...input, - useSessions: (select: (snapshot: SessionListState) => T): T => select({ - ...initial, projectionsBySession: { [PARENT]: { state: 'ready', error: null, values } }, - }), - renderSlot: () => mode.tasks.some(task => task.status !== 'deleted') - ?
Tasks
- : mode.failure === undefined ? null :
{mode.failure}
, - } - const view = render() - expect(screen.queryByRole('button')).toBeNull() - mode.tasks = [{ - id: 'task-1' as TeamTaskId, revision: 1, subject: 'Plan work', description: 'Prepare tasks before spawning workers', - status: 'pending', blockedBy: [], writeScopes: [], ready: true, writeScopeWarnings: [], - }] - view.rerender() - fireEvent.click(screen.getByRole('button', { name: '0 个子智能体' })) - const tree = screen.getByRole('tree') - const board = screen.getByRole('region', { name: 'Shared tasks' }) - expect(tree.compareDocumentPosition(board) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() - expect(screen.getByRole('heading', { name: zh['section.title'] })).toBeTruthy() - expect(screen.getByText(zh['section.empty'])).toBeTruthy() - expect(screen.getAllByRole('dialog')).toHaveLength(1) - mode.tasks = [] - view.rerender() - expect(screen.queryByRole('dialog')).toBeNull() - expect(screen.queryByRole('button')).toBeNull() - mode.tasks = [{ ...sharedTask, status: 'deleted' }] - view.rerender() - expect(screen.queryByRole('button')).toBeNull() - expect(screen.queryByText(zh['section.empty'])).toBeNull() - mode.tasks = [] - mode.failure = 'Invalid task record' - view.rerender() - fireEvent.click(screen.getByRole('button', { name: '0 个子智能体' })) - expect(screen.getByRole('dialog')).toBeTruthy() - expect(screen.queryByRole('heading')).toBeNull() - expect(screen.queryByText(zh['section.empty'])).toBeNull() - expect(document.querySelector('[data-subagent-section-header]')).toBeNull() - view.rerender( select(false)} />) - expect(screen.queryByRole('button')).toBeNull() - mode.enabled = false - view.rerender() - expect(screen.queryByRole('dialog')).toBeNull() - expect(screen.queryByRole('button')).toBeNull() - }) - - it.each([false, true])('keeps child navigation without reading or rendering a task board (listed: %s)', (listed) => { - const input = props(catalog({ team: sharedTeam }), {}, listed ? { - [CHILD]: { ...summary(CHILD, 1), origin: 'subagent', parentId: PARENT }, - } : {}, { parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' }) - const readProjection = vi.fn((): never => { throw new Error('child task-board projection read') }) - const readFooter = vi.fn((): never => { throw new Error('child footer subscription') }) - const renderFooter = vi.fn(() =>
Tasks
) - render(<> - - - ) - fireEvent.click(screen.getByRole('button', { name: /切换子智能体/u })) - expect(screen.getByRole('tree')).toBeTruthy() - expect(screen.queryByRole('region', { name: 'Shared tasks' })).toBeNull() - expect(screen.queryByRole('heading')).toBeNull() - expect(screen.queryByText(zh['section.empty'])).toBeNull() - expect(document.querySelector('[data-subagent-section-header]')).toBeNull() - expect(readProjection).not.toHaveBeenCalled() - expect(readFooter).not.toHaveBeenCalled() - expect(renderFooter).not.toHaveBeenCalled() - }) - it('leaves task-board keys alone and dismisses the shared panel from outside focus', () => { const input = props(catalog()) render(<>