From 55e356d60fc392edbd3ed7386a29cc43c7944175 Mon Sep 17 00:00:00 2001 From: Shigma Date: Tue, 3 Nov 2026 13:49:28 +0800 Subject: [PATCH 001/404] 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/404] 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 2718245916266aa27156d011ebc3690dd73fd4fc Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 14:42:06 +0800 Subject: [PATCH 003/404] fix(sidebar-right): drop the left divider in fullscreen The first dock column draws a left border that separates the sidebar from the conversation. Fullscreen has no conversation beside it, so the border showed as a stray line at the window's left edge. Fixes #7927 Co-authored-by: std4453 <13191718+std4453@users.noreply.github.com> --- .../src/client/shell/SidebarRight.module.css | 6 ++++++ .../tests/sidebar-right-styles.client.spec.ts | 7 ++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css index 09119e640a..d4092a566b 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css @@ -83,6 +83,12 @@ --dsh-dockkit-dock-layer: 40; } +/* Fullscreen has no conversation beside the first column, so dockkit's + column-0 rule separating the two would only edge the window. */ +.panel[data-sidebar-right-panel='fullscreen'] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { + border-left: none; +} + /* No whole-box subtraction here: Electron drag regions are window geometry, not stacking, so a strip row inside this fullscreen content that marks itself `data-window-drag` (ui-dockkit) still owns the drag over its own box, and diff --git a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts index d59a3c843f..6a90c738c1 100644 --- a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts +++ b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts @@ -1,4 +1,4 @@ -/** Right sidebar slide and reveal-flash style contracts. */ +/** Right sidebar slide, fullscreen edge, and reveal-flash style contracts. */ import { readFileSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' @@ -18,6 +18,11 @@ describe('SidebarRight.module.css', () => { + String.raw`\.panel\[data-sidebar-right-open\] ${host}[^{}]*\{\s*transition: none;\s*}`)) }) + it('drops the first column\'s conversation divider in fullscreen', () => { + expect(css).toMatch(new RegExp(String.raw`\.panel\[data-sidebar-right-panel='fullscreen'\] :global\(\[data-dockkit-host='dock'\]\[data-dockkit-column='0'\]\)` + + String.raw` > :global\(\[data-dockkit-pane\]\)\s*\{\s*border-left: none;\s*}`)) + }) + it('draws the reveal glow inside a docked pane above sticky code banners, and outside a floating panel over its own shadow', () => { const pane = String.raw`\.panel :global\(\[data-dockkit-pane\]\[data-sidebar-right-flash\]\)` const float = String.raw`\.panel :global\(\[data-dockkit-float\]\[data-sidebar-right-flash\]\)` From e5e7944ff3b0c9ebddbb4df73d4a5cbfd9a14bab Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 14:49:20 +0800 Subject: [PATCH 004/404] docs(sidebar-right): state the fullscreen divider reason for every platform Co-authored-by: std4453 <13191718+std4453@users.noreply.github.com> --- .../ui-sidebar-right/src/client/shell/SidebarRight.module.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css index d4092a566b..c76b0f6e5f 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css @@ -84,7 +84,7 @@ } /* Fullscreen has no conversation beside the first column, so dockkit's - column-0 rule separating the two would only edge the window. */ + column-0 divider has nothing to separate. */ .panel[data-sidebar-right-panel='fullscreen'] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { border-left: none; } From 8f00cc7f678d4e34bedc661372c0f81aa7330168 Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 15:25:15 +0800 Subject: [PATCH 005/404] docs(sidebar-right): note why the fullscreen divider selector is longer Co-authored-by: std4453 <13191718+std4453@users.noreply.github.com> --- .../ui-sidebar-right/src/client/shell/SidebarRight.module.css | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css index c76b0f6e5f..36314b48e0 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css @@ -84,7 +84,8 @@ } /* Fullscreen has no conversation beside the first column, so dockkit's - column-0 divider has nothing to separate. */ + column-0 divider has nothing to separate. The host attribute and child + combinator outrank dockkit's (0,4,0) rule regardless of stylesheet order. */ .panel[data-sidebar-right-panel='fullscreen'] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { border-left: none; } 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 006/404] 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 d1da247213f9bdf4a5f4a25ba2ce834ad7b65511 Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 15:50:37 +0800 Subject: [PATCH 007/404] fix(sidebar-right): keep the fullscreen divider during the slide The open and close slides move the fullscreen panel across the conversation, so the first column keeps its divider until an opening slide ends and as soon as a closing slide starts. Only the border color changes, so the pane keeps its width. Co-authored-by: std4453 <13191718+std4453@users.noreply.github.com> --- .../src/client/shell/SidebarRight.module.css | 19 +++++++++++++------ .../tests/sidebar-right-styles.client.spec.ts | 11 ++++++++--- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css index 36314b48e0..6caf305fa3 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css @@ -83,11 +83,17 @@ --dsh-dockkit-dock-layer: 40; } -/* Fullscreen has no conversation beside the first column, so dockkit's - column-0 divider has nothing to separate. The host attribute and child - combinator outrank dockkit's (0,4,0) rule regardless of stylesheet order. */ -.panel[data-sidebar-right-panel='fullscreen'] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { - border-left: none; +/* Once open, fullscreen has no conversation beside the first column, so + dockkit's column-0 divider has nothing to separate. While the panel slides + in or out across the conversation the divider stays: an opening keeps it + for the slide's duration, and a closing panel no longer matches. Only the + color changes, so the pane keeps its width. */ +.panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-open] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { + border-left-color: transparent; +} + +.panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-opening] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { + transition: border-left-color 0s linear var(--ds-transition-duration-slow); } /* No whole-box subtraction here: Electron drag regions are window geometry, @@ -132,7 +138,8 @@ .panel :global([data-dockkit-divider]), .panel[data-sidebar-right-open] :global([data-dockkit-host='dock']), .panel[data-sidebar-right-open] :global([data-dockkit-empty]), - .panel[data-sidebar-right-open] :global([data-dockkit-divider]) { + .panel[data-sidebar-right-open] :global([data-dockkit-divider]), + .panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-opening] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { transition: none; } } diff --git a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts index 6a90c738c1..7187986b63 100644 --- a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts +++ b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts @@ -18,9 +18,14 @@ describe('SidebarRight.module.css', () => { + String.raw`\.panel\[data-sidebar-right-open\] ${host}[^{}]*\{\s*transition: none;\s*}`)) }) - it('drops the first column\'s conversation divider in fullscreen', () => { - expect(css).toMatch(new RegExp(String.raw`\.panel\[data-sidebar-right-panel='fullscreen'\] :global\(\[data-dockkit-host='dock'\]\[data-dockkit-column='0'\]\)` - + String.raw` > :global\(\[data-dockkit-pane\]\)\s*\{\s*border-left: none;\s*}`)) + it('hides the first column\'s conversation divider in open fullscreen only after the opening slide', () => { + const fullscreen = String.raw`\.panel\[data-sidebar-right-panel='fullscreen'\]` + const pane = String.raw` :global\(\[data-dockkit-host='dock'\]\[data-dockkit-column='0'\]\) > :global\(\[data-dockkit-pane\]\)` + expect(css).toMatch(new RegExp(String.raw`${fullscreen}\[data-sidebar-right-open\]${pane}\s*\{\s*border-left-color: transparent;\s*}`)) + expect(css).toMatch(new RegExp(String.raw`${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{` + + String.raw`\s*transition: border-left-color 0s linear var\(--ds-transition-duration-slow\);\s*}`)) + expect(css).toMatch(new RegExp(String.raw`@media \(prefers-reduced-motion: reduce\)\s*\{[^{}]*` + + String.raw`${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{\s*transition: none;\s*}`)) }) it('draws the reveal glow inside a docked pane above sticky code banners, and outside a floating panel over its own shadow', () => { From 261a86a1087c94aab090e87861443a605263c0b1 Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 16:17:02 +0800 Subject: [PATCH 008/404] fix(sidebar-right): end the opening only with a docked item's slide A short transition inside the panel ended the opening early, which cancelled the delayed divider change mid-slide. A pane mounted by the opening also starts with the divider now. Co-authored-by: std4453 <13191718+std4453@users.noreply.github.com> --- .../src/client/shell/SidebarRight.module.css | 7 +++++++ .../src/client/shell/SidebarRight.tsx | 14 ++++++++++---- .../ui-sidebar-right/tests/seat.client.spec.tsx | 6 +++++- .../tests/sidebar-right-styles.client.spec.ts | 2 ++ 4 files changed, 24 insertions(+), 5 deletions(-) diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css index 6caf305fa3..4bda4ee3e6 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css @@ -96,6 +96,13 @@ transition: border-left-color 0s linear var(--ds-transition-duration-slow); } +/* A pane mounted by the opening starts with the divider, like one already mounted. */ +@starting-style { + .panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-opening] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { + border-left-color: var(--dsw-alias-border-l4); + } +} + /* No whole-box subtraction here: Electron drag regions are window geometry, not stacking, so a strip row inside this fullscreen content that marks itself `data-window-drag` (ui-dockkit) still owns the drag over its own box, and diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx index e0182a611b..86117bb069 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx @@ -30,7 +30,7 @@ * domain follows each session's store commits, including sessions off screen. */ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' -import type { CSSProperties, ReactNode, RefObject } from 'react' +import type { CSSProperties, ReactNode, RefObject, TransitionEvent } from 'react' import type { ContextMenuTarget } from '@deepseek-ai/dsh-client-ui-context-menu/client' import type { ShortcutCatalogEntry } from '@deepseek-ai/dsh-client-shortcuts/client' import { IconPanelLeftOutlineRegular, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' @@ -305,6 +305,12 @@ function PanelChrome({ sessionId, fullscreen, actions, t, shortcuts, toggleFulls ) } +/** Whether a bubbled transition end is the open slide of a docked Grid item, not a short transition inside one. */ +function slideEnded(event: TransitionEvent): boolean { + return event.propertyName === 'transform' + && (event.target as Element).matches("[data-dockkit-host='dock'], [data-dockkit-empty], [data-dockkit-divider]") +} + /** * The panel: the docked surface with the two controls in its top-right strip, * anchored to the frame's right edge and slid off it while collapsed. @@ -324,8 +330,8 @@ function SidebarPanel(panel: PanelProps & { width: number; panelRef: RefObject { setOpening(false) } : undefined} + onTransitionEnd={opening ? (event) => { if (slideEnded(event)) setOpening(false) } : undefined} // Dockkit hides individual docked hosts; floating descendants remain accessible. aria-hidden={(!expanded && surface.layout.floats.length === 0) || undefined} > diff --git a/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx b/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx index c6ae78c2e8..106b3b6bf7 100644 --- a/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx +++ b/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx @@ -626,7 +626,11 @@ describe('RightbarSeat presentation', () => { // The tab the opening seeds mounts under the mark, so it starts at the closed position. const host = element(h.view.container, "[data-dockkit-host='dock']") expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(true) - fireEvent.transitionEnd(host) + // Short transitions inside an item, or other properties, do not end the slide. + fireEvent.transitionEnd(element(host, '[data-dockkit-pane]'), { propertyName: 'transform' }) + fireEvent.transitionEnd(host, { propertyName: 'opacity' }) + expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(true) + fireEvent.transitionEnd(host, { propertyName: 'transform' }) expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(false) act(() => { h.actions.splitPane(SESSION) }) expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(false) diff --git a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts index 7187986b63..19cbfb270f 100644 --- a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts +++ b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts @@ -24,6 +24,8 @@ describe('SidebarRight.module.css', () => { expect(css).toMatch(new RegExp(String.raw`${fullscreen}\[data-sidebar-right-open\]${pane}\s*\{\s*border-left-color: transparent;\s*}`)) expect(css).toMatch(new RegExp(String.raw`${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{` + String.raw`\s*transition: border-left-color 0s linear var\(--ds-transition-duration-slow\);\s*}`)) + expect(css).toMatch(new RegExp(String.raw`@starting-style\s*\{\s*${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{` + + String.raw`\s*border-left-color: var\(--dsw-alias-border-l4\);\s*}\s*}`)) expect(css).toMatch(new RegExp(String.raw`@media \(prefers-reduced-motion: reduce\)\s*\{[^{}]*` + String.raw`${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{\s*transition: none;\s*}`)) }) From 0dd0bd18cdb3b81e023e9764dd04abaf14492cf9 Mon Sep 17 00:00:00 2001 From: Shigma Date: Thu, 5 Nov 2026 16:26:40 +0800 Subject: [PATCH 009/404] 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 010/404] 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 011/404] 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 012/404] 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 013/404] 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 014/404] 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 015/404] 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 e9591154b4919682faf539e5ea48951d189b3eae Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 17:57:11 +0800 Subject: [PATCH 016/404] fix(sidebar-right): clip the fullscreen divider past the window edge Make the fullscreen panel 1px wider than the viewport instead of hiding the first column's divider with state-dependent rules. At rest the divider sits past the left edge, where the frame clips it, and the pane's content box matches the viewport; during the open and close slides the divider moves with the panel and stays visible. Co-authored-by: std4453 <13191718+std4453@users.noreply.github.com> --- .../src/client/shell/SidebarRight.module.css | 23 +------------------ .../src/client/shell/SidebarRight.tsx | 21 ++++++++--------- .../tests/seat.client.spec.tsx | 9 +++----- .../tests/sidebar-right-styles.client.spec.ts | 14 +---------- 4 files changed, 14 insertions(+), 53 deletions(-) diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css index 454acbcd26..94d08c4f24 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css @@ -83,26 +83,6 @@ --dsh-dockkit-dock-layer: 40; } -/* Once open, fullscreen has no conversation beside the first column, so - dockkit's column-0 divider has nothing to separate. While the panel slides - in or out across the conversation the divider stays: an opening keeps it - for the slide's duration, and a closing panel no longer matches. Only the - color changes, so the pane keeps its width. */ -.panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-open] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { - border-left-color: transparent; -} - -.panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-opening] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { - transition: border-left-color 0s linear var(--ds-transition-duration-slow); -} - -/* A pane mounted by the opening starts with the divider, like one already mounted. */ -@starting-style { - .panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-opening] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { - border-left-color: var(--dsw-alias-border-l4); - } -} - /* Dockkit owns its pane exclusions and marked strip rows. Electron composes their boxes in DOM order: a pane subtracts its box, then a marked strip adds its row back. ui-web excludes controls within that row and body portals; @@ -144,8 +124,7 @@ .panel :global([data-dockkit-divider]), .panel[data-sidebar-right-open] :global([data-dockkit-host='dock']), .panel[data-sidebar-right-open] :global([data-dockkit-empty]), - .panel[data-sidebar-right-open] :global([data-dockkit-divider]), - .panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-opening] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { + .panel[data-sidebar-right-open] :global([data-dockkit-divider]) { transition: none; } } diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx index 86117bb069..2659481ab6 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx @@ -30,7 +30,7 @@ * domain follows each session's store commits, including sessions off screen. */ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' -import type { CSSProperties, ReactNode, RefObject, TransitionEvent } from 'react' +import type { CSSProperties, ReactNode, RefObject } from 'react' import type { ContextMenuTarget } from '@deepseek-ai/dsh-client-ui-context-menu/client' import type { ShortcutCatalogEntry } from '@deepseek-ai/dsh-client-shortcuts/client' import { IconPanelLeftOutlineRegular, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' @@ -305,12 +305,6 @@ function PanelChrome({ sessionId, fullscreen, actions, t, shortcuts, toggleFulls ) } -/** Whether a bubbled transition end is the open slide of a docked Grid item, not a short transition inside one. */ -function slideEnded(event: TransitionEvent): boolean { - return event.propertyName === 'transform' - && (event.target as Element).matches("[data-dockkit-host='dock'], [data-dockkit-empty], [data-dockkit-divider]") -} - /** * The panel: the docked surface with the two controls in its top-right strip, * anchored to the frame's right edge and slid off it while collapsed. @@ -330,8 +324,8 @@ function SidebarPanel(panel: PanelProps & { width: number; panelRef: RefObject { if (slideEnded(event)) setOpening(false) } : undefined} + onTransitionEnd={opening ? () => { setOpening(false) } : undefined} // Dockkit hides individual docked hosts; floating descendants remain accessible. aria-hidden={(!expanded && surface.layout.floats.length === 0) || undefined} > diff --git a/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx b/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx index 106b3b6bf7..3d1f634711 100644 --- a/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx +++ b/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx @@ -626,11 +626,7 @@ describe('RightbarSeat presentation', () => { // The tab the opening seeds mounts under the mark, so it starts at the closed position. const host = element(h.view.container, "[data-dockkit-host='dock']") expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(true) - // Short transitions inside an item, or other properties, do not end the slide. - fireEvent.transitionEnd(element(host, '[data-dockkit-pane]'), { propertyName: 'transform' }) - fireEvent.transitionEnd(host, { propertyName: 'opacity' }) - expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(true) - fireEvent.transitionEnd(host, { propertyName: 'transform' }) + fireEvent.transitionEnd(host) expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(false) act(() => { h.actions.splitPane(SESSION) }) expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(false) @@ -657,7 +653,8 @@ describe('RightbarSeat presentation', () => { expect(panel.style.width).toBe('420px') fireEvent.click(element(h.view.container, '[data-sidebar-right-mode]')) expect(h.layout().mode).toBe('fullscreen') - expect(panel.style.width).toBe('100vw') + expect(panel.style.width).toBe('calc(1px + 100vw)') + expect(panel.style.getPropertyValue('--dsh-sidebar-width')).toBe('calc(100vw + 1px)') expect(panel.dataset['sidebarRightPanel']).toBe('fullscreen') expect(element(h.view.container, '[data-tab-body]')).toBe(body) expect(h.frame.openRightbar).toHaveBeenLastCalledWith(true, true) diff --git a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts index 19cbfb270f..d59a3c843f 100644 --- a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts +++ b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts @@ -1,4 +1,4 @@ -/** Right sidebar slide, fullscreen edge, and reveal-flash style contracts. */ +/** Right sidebar slide and reveal-flash style contracts. */ import { readFileSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' @@ -18,18 +18,6 @@ describe('SidebarRight.module.css', () => { + String.raw`\.panel\[data-sidebar-right-open\] ${host}[^{}]*\{\s*transition: none;\s*}`)) }) - it('hides the first column\'s conversation divider in open fullscreen only after the opening slide', () => { - const fullscreen = String.raw`\.panel\[data-sidebar-right-panel='fullscreen'\]` - const pane = String.raw` :global\(\[data-dockkit-host='dock'\]\[data-dockkit-column='0'\]\) > :global\(\[data-dockkit-pane\]\)` - expect(css).toMatch(new RegExp(String.raw`${fullscreen}\[data-sidebar-right-open\]${pane}\s*\{\s*border-left-color: transparent;\s*}`)) - expect(css).toMatch(new RegExp(String.raw`${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{` - + String.raw`\s*transition: border-left-color 0s linear var\(--ds-transition-duration-slow\);\s*}`)) - expect(css).toMatch(new RegExp(String.raw`@starting-style\s*\{\s*${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{` - + String.raw`\s*border-left-color: var\(--dsw-alias-border-l4\);\s*}\s*}`)) - expect(css).toMatch(new RegExp(String.raw`@media \(prefers-reduced-motion: reduce\)\s*\{[^{}]*` - + String.raw`${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{\s*transition: none;\s*}`)) - }) - it('draws the reveal glow inside a docked pane above sticky code banners, and outside a floating panel over its own shadow', () => { const pane = String.raw`\.panel :global\(\[data-dockkit-pane\]\[data-sidebar-right-flash\]\)` const float = String.raw`\.panel :global\(\[data-dockkit-float\]\[data-sidebar-right-flash\]\)` From fa0b1522cb5ddc120b2135c503a8cbc4e9e5c5ac Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 18:41:39 +0800 Subject: [PATCH 017/404] test(web): expect the fullscreen sidebar 1px past the left edge Co-authored-by: std4453 <13191718+std4453@users.noreply.github.com> --- apps/web/tests/details-session-lifecycle.e2e.ts | 14 +++++++------- apps/web/tests/sidebar-right.e2e.ts | 12 ++++++------ apps/web/tests/support.ts | 10 ++++++++++ .../details-session-lifecycle/sidebar.expected.md | 12 ++++++------ 4 files changed, 29 insertions(+), 19 deletions(-) diff --git a/apps/web/tests/details-session-lifecycle.e2e.ts b/apps/web/tests/details-session-lifecycle.e2e.ts index e73eaa5d0b..05da4a6afa 100644 --- a/apps/web/tests/details-session-lifecycle.e2e.ts +++ b/apps/web/tests/details-session-lifecycle.e2e.ts @@ -10,7 +10,7 @@ import { fixtureUserPrompts, launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' -import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts' +import { connectFreshWorkspace, fullscreenBox, newEnglishPage, saveFailureShot } from './support.ts' const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/details-session-lifecycle', import.meta.url)) const HANDLES_EXPECTED = join(SNAPSHOT_DIR, 'handles.expected.md') @@ -110,8 +110,8 @@ async function sidebarSnapshot(page: Page) { mode: panel.getAttribute('data-sidebar-right-panel'), panelContentWidth: expanded ? Math.round(Number.parseFloat(style.width)) : 0, panelOuterWidth: expanded ? Math.round(rect.width) : 0, - coversViewport: expanded && rect.x === 0 && rect.y === 0 - && Math.round(rect.width) === window.innerWidth && Math.round(rect.height) === window.innerHeight, + coversViewport: expanded && rect.x === -1 && rect.y === 0 + && Math.round(rect.width) === window.innerWidth + 1 && Math.round(rect.height) === window.innerHeight, resizeHandleWidth: handle === null ? 0 : Math.round(handle.getBoundingClientRect().width), expandedDirectories: [...panel.querySelectorAll('[data-files-entry="directory"] button[aria-expanded="true"]')] .map(button => button.textContent?.trim()), @@ -195,7 +195,7 @@ describe.skipIf(MODE === 'record')('web e2e: details panel follows the current S await expect.poll(() => blankColumn.locator('[data-dockkit-host="dock"]:not([hidden])').evaluate(element => getComputedStyle(element).transform)) .toBe('none') await expect.poll(() => blankColumn.locator('[data-sidebar-right-panel]').boundingBox()) - .toEqual({ x: 0, y: 0, width: 767, height: blankViewport.height }) + .toEqual(fullscreenBox({ width: 767, height: blankViewport.height })) // A preview the files page opened starts with its tree hidden; shown, the tree fills the viewport. const treeToggle = blankColumn.locator('[data-files-navigator-toggle]') await expect.poll(() => treeToggle.getAttribute('aria-expanded')).toBe('false') @@ -360,7 +360,7 @@ describe.skipIf(MODE === 'record')('web e2e: details panel follows the current S await checkpoint('A normal: two panes') await column.locator('[data-sidebar-right-mode="fullscreen"]').click() - await expect.poll(() => panel.boundingBox()).toEqual({ x: 0, y: 0, ...viewport }) + await expect.poll(() => panel.boundingBox()).toEqual(fullscreenBox(viewport)) expect(await columns(page)).toEqual(normalColumns) expect(await sidebarSnapshot(page)).toMatchObject({ mode: 'fullscreen', resizeHandleWidth: 0, coversViewport: true }) expect(await paneSnapshot(page)).toEqual(retainedA) @@ -395,7 +395,7 @@ describe.skipIf(MODE === 'record')('web e2e: details panel follows the current S expect(await panel.getAttribute('data-sidebar-right-panel')).toBe('fullscreen') expect(await paneSnapshot(page)).toEqual(retainedA) await open() - await expect.poll(() => panel.boundingBox()).toEqual({ x: 0, y: 0, ...viewport }) + await expect.poll(() => panel.boundingBox()).toEqual(fullscreenBox(viewport)) expect(await paneSnapshot(page)).toEqual(retainedA) await checkpoint('A restored: manual fullscreen, tabs, and panes') await column.locator('[data-sidebar-right-mode="push"]').click() @@ -433,7 +433,7 @@ describe.skipIf(MODE === 'record')('web e2e: details panel follows the current S await page.locator('[data-sidebar-right-expand]').click() await expect.poll(() => columns(page)).toEqual([420, viewport.width - 420 - normalWidth, normalWidth]) await page.setViewportSize({ width: 767, height: viewport.height }) - await expect.poll(() => panel.boundingBox()).toEqual({ x: 0, y: 0, width: 767, height: viewport.height }) + await expect.poll(() => panel.boundingBox()).toEqual(fullscreenBox({ width: 767, height: viewport.height })) await expect.poll(() => columns(page)).toEqual([0, 767, 0]) expect(await sidebarSnapshot(page)).toMatchObject({ mode: 'fullscreen', resizeHandleWidth: 0, coversViewport: true }) await checkpoint('A automatic fullscreen at 767px') diff --git a/apps/web/tests/sidebar-right.e2e.ts b/apps/web/tests/sidebar-right.e2e.ts index 461947ed21..c66eba54db 100644 --- a/apps/web/tests/sidebar-right.e2e.ts +++ b/apps/web/tests/sidebar-right.e2e.ts @@ -26,7 +26,7 @@ import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' import { createMessage, createUserMessage } from '@deepseek-ai/dsh-llm' import { acknowledgeReloadConnectionLoss, launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts' import { - connectFreshWorkspace, newEnglishPage, saveFailureShot, ZH_BROWSER_LOCALE, + connectFreshWorkspace, fullscreenBox, newEnglishPage, saveFailureShot, ZH_BROWSER_LOCALE, } from './support.ts' /** The produced file the seeded turn writes, and what the preview should show. */ @@ -524,7 +524,7 @@ describe('web e2e: shipped right Sidebar', () => { expect(await width(column)).toBe(trackWidth) const viewport = page.viewportSize() if (viewport === null) throw new Error('expected a fixed viewport') - await expect.poll(async () => await panel.boundingBox()).toEqual({ x: 0, y: 0, ...viewport }) + await expect.poll(async () => await panel.boundingBox()).toEqual(fullscreenBox(viewport)) expect(await expandOf(page).count()).toBe(0) expect(await frame.locator('[data-side="rightbar"]').count()).toBe(0) await shot(page, '03-fullscreen-panel') @@ -558,7 +558,7 @@ describe('web e2e: shipped right Sidebar', () => { await frame.evaluate(async (node) => { await Promise.allSettled(node.getAnimations().map(animation => animation.finished)) }) const normalColumns = (await geometry()).columns await column.locator('[data-sidebar-right-mode="fullscreen"]').click() - await expect.poll(() => panel.boundingBox()).toEqual({ x: 0, y: 0, ...viewport }) + await expect.poll(() => panel.boundingBox()).toEqual(fullscreenBox(viewport)) await column.locator('[data-sidebar-right-toggle]').click() await Promise.all([ panel.evaluate(async (node) => { @@ -586,7 +586,7 @@ describe('web e2e: shipped right Sidebar', () => { await held.evaluate((state) => { (state.animation as Animation).finish() }) await expect.poll(() => frame.getAttribute('data-rightbar-fullscreen')).toBe('true') - expect(await panel.boundingBox()).toEqual({ x: 0, y: 0, ...viewport }) + expect(await panel.boundingBox()).toEqual(fullscreenBox(viewport)) expect(await geometry()).toEqual({ columns: normalColumns, transition: 'none', handles: ['none'], animatingGrid: false }) const exit = await holdPanelSlide(panel) @@ -621,7 +621,7 @@ describe('web e2e: shipped right Sidebar', () => { await expect.poll(() => frame.getAttribute('data-rightbar-fullscreen')).toBeNull() await expandOf(page).click() await expect.poll(() => frame.getAttribute('data-rightbar-fullscreen')).toBe('true') - expect(await panel.boundingBox()).toEqual({ x: 0, y: 0, ...viewport }) + expect(await panel.boundingBox()).toEqual(fullscreenBox(viewport)) expect((await geometry()).columns).toBe(normalColumns) expect((await geometry()).animatingGrid).toBe(false) } finally { @@ -733,7 +733,7 @@ describe('web e2e: shipped right Sidebar', () => { await page.setViewportSize({ width: 767, height: viewport.height }) await expect.poll(async () => await panel.getAttribute('data-sidebar-right-panel')).toBe('fullscreen') - await expect.poll(async () => await width(panel)).toBe(767) + await expect.poll(async () => await width(panel)).toBe(768) await expect.poll(() => frame.getAttribute('data-rightbar-fullscreen')).toBe('true') expect(await expandOf(page).count()).toBe(0) expect(await frame.locator('[data-side="rightbar"]').count()).toBe(0) diff --git a/apps/web/tests/support.ts b/apps/web/tests/support.ts index cda15bafaf..ec7b5b1404 100644 --- a/apps/web/tests/support.ts +++ b/apps/web/tests/support.ts @@ -468,3 +468,13 @@ export async function openSettings(page: Page, locale: 'en' | 'zh' | 'ja'): Prom await trigger.click() await page.getByRole('menuitem', { name: labels[locale][1], exact: true }).click() } + +/** + * The right Sidebar's fullscreen panel box: 1px wider than the viewport, so the + * first column's divider sits past the window's left edge where the frame clips it. + * @param viewport - the page viewport size. + * @returns the panel's expected bounding box. + */ +export function fullscreenBox(viewport: { width: number; height: number }): { x: number; y: number; width: number; height: number } { + return { x: -1, y: 0, width: viewport.width + 1, height: viewport.height } +} diff --git a/snapshots/web/details-session-lifecycle/sidebar.expected.md b/snapshots/web/details-session-lifecycle/sidebar.expected.md index f205ed9765..4607cf35ed 100644 --- a/snapshots/web/details-session-lifecycle/sidebar.expected.md +++ b/snapshots/web/details-session-lifecycle/sidebar.expected.md @@ -64,8 +64,8 @@ "columnTransition": "none", "expanded": true, "mode": "fullscreen", - "panelContentWidth": 1680, - "panelOuterWidth": 1680, + "panelContentWidth": 1681, + "panelOuterWidth": 1681, "coversViewport": true, "resizeHandleWidth": 0, "expandedDirectories": [], @@ -197,8 +197,8 @@ "columnTransition": "none", "expanded": true, "mode": "fullscreen", - "panelContentWidth": 1680, - "panelOuterWidth": 1680, + "panelContentWidth": 1681, + "panelOuterWidth": 1681, "coversViewport": true, "resizeHandleWidth": 0, "expandedDirectories": [], @@ -424,8 +424,8 @@ "columnTransition": "none", "expanded": true, "mode": "fullscreen", - "panelContentWidth": 767, - "panelOuterWidth": 767, + "panelContentWidth": 768, + "panelOuterWidth": 768, "coversViewport": true, "resizeHandleWidth": 0, "expandedDirectories": [], From 6d44ea055b7b41a0342524e7f17fa1bb6b5088e1 Mon Sep 17 00:00:00 2001 From: Shigma Date: Thu, 5 Nov 2026 19:29:17 +0800 Subject: [PATCH 018/404] refactor(cordis): migrate remaining Include-dialect YAML call sites --- apps/cli/tests/profiles/official-installer-packed.e2e.ts | 4 ++-- apps/cli/tests/profiles/webhook-packed.e2e.ts | 3 ++- apps/web/tests/cua-optin.e2e.ts | 8 ++++---- apps/web/tests/session-log-upload.e2e.ts | 4 ++-- packages/boot/app-boot/src/config-schema/collect.ts | 2 +- packages/subagent/subagent-claude-code/package.json | 1 + .../tests/subagent-claude-code.spec.ts | 4 ++-- packages/subagent/subagent-codex/package.json | 1 + .../subagent/subagent-codex/tests/subagent-codex.spec.ts | 4 ++-- pnpm-lock.yaml | 6 ++++++ vendor/README.md | 2 +- vendor/include/src/index.ts | 6 +++--- 12 files changed, 27 insertions(+), 18 deletions(-) diff --git a/apps/cli/tests/profiles/official-installer-packed.e2e.ts b/apps/cli/tests/profiles/official-installer-packed.e2e.ts index e9039e8a5a..699f8deb7c 100644 --- a/apps/cli/tests/profiles/official-installer-packed.e2e.ts +++ b/apps/cli/tests/profiles/official-installer-packed.e2e.ts @@ -5,8 +5,8 @@ import { join } from 'node:path' import { createInterface } from 'node:readline' import { fileURLToPath } from 'node:url' import { execa } from 'execa' -import yaml from 'js-yaml' import { expect, it, onTestFinished } from 'vitest' +import { stringifyEntryYaml } from '@deepseek-ai/cordis-plugin-include' import type { BundleInfo, ChangeResult } from '@deepseek-ai/dsh-plugin-manager' import { getDshRuntimeVersion } from '../../../../packages/boot/app-boot/src/plugin-compatibility.ts' import { generateOfficialBundleCatalog } from '../../../../scripts/gen-official-bundle-catalog.ts' @@ -118,7 +118,7 @@ it.skipIf(!built)('installs the exported registry\'s local closure and switches const observer = join(temporary, 'official-installer-observer.mjs') await writeFile(observer, await readFile(new URL('./fixtures/official-installer-observer.mjs', import.meta.url), 'utf8')) const patch = join(temporary, 'official-installer.patch.yml') - await writeFile(patch, yaml.dump([{ insert: [{ id: 'official-installer-observer', name: observer, + await writeFile(patch, stringifyEntryYaml([{ insert: [{ id: 'official-installer-observer', name: observer, config: { registry: registry.url, profile, diff --git a/apps/cli/tests/profiles/webhook-packed.e2e.ts b/apps/cli/tests/profiles/webhook-packed.e2e.ts index 3844ceb22b..ac0214a76d 100644 --- a/apps/cli/tests/profiles/webhook-packed.e2e.ts +++ b/apps/cli/tests/profiles/webhook-packed.e2e.ts @@ -7,6 +7,7 @@ import { fileURLToPath } from 'node:url' import { execa } from 'execa' import yaml from 'js-yaml' import { expect, it } from 'vitest' +import { stringifyEntryYaml } from '@deepseek-ai/cordis-plugin-include' import { assertInstalledTree, createPackedInstallation } from './packed-installation.ts' const root = fileURLToPath(new URL('../../../..', import.meta.url)) @@ -64,7 +65,7 @@ export function apply(ctx) { } `) const patch = join(temporary, 'test.patch.yml') - await writeFile(patch, yaml.dump([ + await writeFile(patch, stringifyEntryYaml([ { id: 'session-telemetry-otel', disabled: true }, { id: 'github-webhook-ingress', insert: [{ id: 'observe-packed-ingress', name: observer }] }, ])) diff --git a/apps/web/tests/cua-optin.e2e.ts b/apps/web/tests/cua-optin.e2e.ts index 77ec920da5..d7edef699a 100644 --- a/apps/web/tests/cua-optin.e2e.ts +++ b/apps/web/tests/cua-optin.e2e.ts @@ -8,7 +8,7 @@ import { readProfileManifest } from '@deepseek-ai/dsh-app-boot' import { SessionId } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-ptc-runtime' import type {} from '@deepseek-ai/dsh-agent-preset-registry' -import { load } from 'js-yaml' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' import { expect, it, vi } from 'vitest' import { captureStableAria, compareOrRefreshGolden, launchWebScaffold, webSnapshotMode, type WebScaffold } from './scaffold.ts' import { connectFreshWorkspaceZh, ZH_BROWSER_LOCALE } from './support.ts' @@ -151,9 +151,9 @@ it.skipIf(process.platform !== 'darwin').each([ expect(scaffold.ctx.settings.describe().find(row => row.ns === 'ui-settings')?.value).toMatchObject({ enabled: codingTools }) expect(saved).not.toContain('executionMode:') if (selectedDefault === undefined) { - expect(load(saved)).not.toEqual(expect.arrayContaining([expect.objectContaining({ id: 'agent-preset-registry' })])) + expect(parseEntryYaml(saved)).not.toEqual(expect.arrayContaining([expect.objectContaining({ id: 'agent-preset-registry' })])) } else { - expect(load(saved)).toEqual(expect.arrayContaining([ + expect(parseEntryYaml(saved)).toEqual(expect.arrayContaining([ expect.objectContaining({ id: 'agent-preset-registry', config: { default: 'standard', selectedDefault } }), ])) } @@ -232,7 +232,7 @@ it.skipIf(process.platform !== 'darwin').each([ expect(scaffold.ctx.tools.schemas(ptcAgent).some(tool => tool.name === 'cua')).toBe(true) expect((await runtime.run(runtime.resolve({ program, bindings: [], stateOwner: owner }))).value).toBe(3) const confirmedSettings = await readFile(settingsPath, 'utf8') - expect(load(confirmedSettings)).toEqual(expect.arrayContaining([ + expect(parseEntryYaml(confirmedSettings)).toEqual(expect.arrayContaining([ expect.objectContaining({ id: 'agent-preset-registry', config: { default: 'standard', selectedDefault: 'ptc' } }), ])) await toggle.click() diff --git a/apps/web/tests/session-log-upload.e2e.ts b/apps/web/tests/session-log-upload.e2e.ts index 09a3c4444c..8b26c3c5f9 100644 --- a/apps/web/tests/session-log-upload.e2e.ts +++ b/apps/web/tests/session-log-upload.e2e.ts @@ -3,8 +3,8 @@ import { mkdtemp, rm, writeFile, readFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { chromium } from 'playwright' -import yaml from 'js-yaml' import { expect, it, onTestFinished } from 'vitest' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' import { credentialRef } from '@deepseek-ai/dsh-credentials' import { startMockLlmServer } from '@deepseek-ai/dsh-llm-mock-server' import { launchWebScaffold, webSnapshotMode } from './scaffold.ts' @@ -44,7 +44,7 @@ it.skipIf(webSnapshotMode() === 'record')('persists the upload switch and omits await toggle.click() await expect.poll(() => toggle.getAttribute('aria-checked')).toBe(String(enabled)) await expect.poll(async () => { - const patches = yaml.load(await readFile(join(scaffold.harnessHome, 'profiles/scaffold/cordis.patch.yml'), 'utf8')) as { id: string; config?: { enabled?: boolean } }[] + const patches = parseEntryYaml(await readFile(join(scaffold.harnessHome, 'profiles/scaffold/cordis.patch.yml'), 'utf8')) as { id: string; config?: { enabled?: boolean } }[] return patches.find(patch => patch.id === 'session-log-deepseek')?.config?.enabled ?? true }).toBe(enabled) await page.keyboard.press('Escape') diff --git a/packages/boot/app-boot/src/config-schema/collect.ts b/packages/boot/app-boot/src/config-schema/collect.ts index ab18fc035c..0eed38de5c 100644 --- a/packages/boot/app-boot/src/config-schema/collect.ts +++ b/packages/boot/app-boot/src/config-schema/collect.ts @@ -150,7 +150,7 @@ export async function collectConfigSchemas( source = extension === '.json' ? JSON.parse(content) : parseEntryYaml(content) } catch (error) { // Parser messages can quote configuration values; retain only the file and location. - const position = extension === '.json' ? undefined : entryYamlErrorPosition(error) + const position = 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/subagent/subagent-claude-code/package.json b/packages/subagent/subagent-claude-code/package.json index bd59808055..55f99d0db1 100644 --- a/packages/subagent/subagent-claude-code/package.json +++ b/packages/subagent/subagent-claude-code/package.json @@ -55,6 +55,7 @@ }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/cordis-plugin-include": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-app-boot": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", diff --git a/packages/subagent/subagent-claude-code/tests/subagent-claude-code.spec.ts b/packages/subagent/subagent-claude-code/tests/subagent-claude-code.spec.ts index 4b46c397d5..faf32eb43a 100644 --- a/packages/subagent/subagent-claude-code/tests/subagent-claude-code.spec.ts +++ b/packages/subagent/subagent-claude-code/tests/subagent-claude-code.spec.ts @@ -15,7 +15,7 @@ import type { } from '@anthropic-ai/claude-agent-sdk' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' -import * as yaml from 'js-yaml' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' import { afterEach, beforeEach, @@ -392,7 +392,7 @@ describe('task admission and package contracts', () => { ) } - const parsed = yaml.load(readFileSync(resolve(root, manifest.dsh!.bundle!.patch!), 'utf8')) + const parsed = parseEntryYaml(readFileSync(resolve(root, manifest.dsh!.bundle!.patch!), 'utf8')) expect(parsed).toEqual([{ insert: [ { id: 'subagent-claude-code', name: '@deepseek-ai/dsh-subagent-claude-code' }, { id: 'tool-subagent-claude-code', name: '@deepseek-ai/dsh-tool-subagent', config: { diff --git a/packages/subagent/subagent-codex/package.json b/packages/subagent/subagent-codex/package.json index 05df46cbc9..014a19366b 100644 --- a/packages/subagent/subagent-codex/package.json +++ b/packages/subagent/subagent-codex/package.json @@ -53,6 +53,7 @@ }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/cordis-plugin-include": "workspace:~", "@deepseek-ai/cordis-plugin-loader": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-app-boot": "workspace:*", diff --git a/packages/subagent/subagent-codex/tests/subagent-codex.spec.ts b/packages/subagent/subagent-codex/tests/subagent-codex.spec.ts index 4e267275f5..7dbb71fb64 100644 --- a/packages/subagent/subagent-codex/tests/subagent-codex.spec.ts +++ b/packages/subagent/subagent-codex/tests/subagent-codex.spec.ts @@ -7,7 +7,7 @@ import { PassThrough } from 'node:stream' import { fileURLToPath } from 'node:url' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' -import * as yaml from 'js-yaml' +import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include' import { describe, expect, it, vi } from 'vitest' import type { Agent } from '@deepseek-ai/dsh-agent' import type { ContentBlock } from '@deepseek-ai/dsh-llm' @@ -405,7 +405,7 @@ describe('task admission and package contracts', () => { ) } - const parsed = yaml.load(readFileSync(resolve(root, manifest.dsh!.bundle!.patch!), 'utf8')) + const parsed = parseEntryYaml(readFileSync(resolve(root, manifest.dsh!.bundle!.patch!), 'utf8')) expect(parsed).toEqual([{ insert: [ { id: 'subagent-codex', name: '@deepseek-ai/dsh-subagent-codex' }, { id: 'tool-subagent-codex', name: '@deepseek-ai/dsh-tool-subagent', config: { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 00c3c94fb1..23f2f3d7c4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -16328,6 +16328,9 @@ importers: '@deepseek-ai/cordis': specifier: workspace:~ version: link:../../../vendor/cordis + '@deepseek-ai/cordis-plugin-include': + specifier: workspace:~ + version: link:../../../vendor/include '@deepseek-ai/dsh-agent': specifier: workspace:* version: link:../../core/agent @@ -16398,6 +16401,9 @@ importers: '@deepseek-ai/cordis': specifier: workspace:~ version: link:../../../vendor/cordis + '@deepseek-ai/cordis-plugin-include': + specifier: workspace:~ + version: link:../../../vendor/include '@deepseek-ai/cordis-plugin-loader': specifier: workspace:~ version: link:../../../vendor/loader diff --git a/vendor/README.md b/vendor/README.md index bb51a6381d..b59f8bd765 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`, 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`. +- **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` always writes with `noRefs` and offers no option to emit aliases, 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/src/index.ts b/vendor/include/src/index.ts index 2f905bbe3e..b8e12bd6a7 100644 --- a/vendor/include/src/index.ts +++ b/vendor/include/src/index.ts @@ -41,8 +41,8 @@ export function parseEntryYaml(content: string): unknown { } /** - * 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. + * Serialize a value in Include's YAML dialect. JavaScript expression nodes are written as `!!js` scalars. The output + * never contains anchors or aliases: repeated object references are written out in full, and no option changes this. * @param value - entry list, patch list, or entry fragment to serialize. * @param options - output formatting. * @returns YAML text ending with a newline. @@ -53,7 +53,7 @@ export function stringifyEntryYaml(value: unknown, options: EntryYamlStringifyOp /** * Locate a syntax error thrown by {@link parseEntryYaml}. - * @param error - value thrown by {@link parseEntryYaml}. + * @param error - any caught value; only a parse error thrown by {@link parseEntryYaml} yields a position. * @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 { From 1511a6ed442c207919142a4b0e6c4916f96d2c3b Mon Sep 17 00:00:00 2001 From: Shigma Date: Wed, 4 Nov 2026 23:45:12 +0800 Subject: [PATCH 019/404] chore(cordis): upgrade core to 4.0.0-rc.12 --- .../fixtures/subagent-settlement-fence.ts | 6 +- .../tests/default-product-isolation.e2e.ts | 6 +- docs/cordis-api/context.i18n.yaml | 38 +++--- docs/cordis-api/context.md | 59 ++++----- docs/cordis-api/context.zh.md | 59 ++++----- docs/cordis-api/fiber.i18n.yaml | 96 +++++++-------- docs/cordis-api/fiber.md | 74 ++++++++---- docs/cordis-api/fiber.zh.md | 74 ++++++++---- docs/cordis-api/inherited.md | 2 +- docs/cordis-api/service.i18n.yaml | 43 ++++--- docs/cordis-api/service.md | 57 +++++---- docs/cordis-api/service.zh.md | 57 +++++---- .../guide.i18n.yaml | 16 +++ .../guide.md | 29 +++++ .../guide.zh.md | 29 +++++ packages/api/gateway/tests/peer.ts | 10 +- .../tests/transport.host.spec.ts | 2 +- packages/boot/app-boot/tests/app-boot.spec.ts | 2 +- .../boot/app-boot/tests/config-reload.spec.ts | 2 +- packages/boot/config-editor/src/index.ts | 6 +- packages/boot/hmr/src/index.ts | 2 +- .../boot/hmr/tests/package-reload.spec.ts | 2 +- packages/bundle/web-app/src/index.ts | 8 +- packages/client/connection/src/index.ts | 4 +- .../experimental/auto-review/src/index.ts | 4 +- .../auto-review/tests/auto-review.spec.ts | 4 +- .../inspector/src/shared/cordis/observer.ts | 4 +- .../src/client/api-catalog.ts | 2 +- .../tests/sandbox-context.spec.ts | 19 ++- .../extensions/tool-cordis/src/api-catalog.ts | 2 +- packages/mcp/mcp-client/src/index.ts | 4 +- .../preset/agent-preset-registry/src/mount.ts | 2 +- packages/sdk/server/src/index.ts | 4 +- packages/settings/settings/src/index.ts | 2 +- .../fixtures/subagent-send-message-fence.ts | 10 +- packages/typert/protocol/src/index.ts | 4 +- scripts/cordis-core-api.spec.ts | 2 +- scripts/cordis-core-lifecycle.spec.ts | 3 +- scripts/cordis-core-rc12.spec.ts | 114 ++++++++++++++++++ scripts/gen-cordis-catalog.ts | 2 +- vendor/README.md | 9 +- vendor/cordis/src/context.ts | 21 ++-- vendor/cordis/src/events.ts | 12 +- vendor/cordis/src/fiber.ts | 58 ++++++--- vendor/cordis/src/logger.ts | 27 ++--- vendor/cordis/src/reflect.ts | 56 ++++++--- vendor/cordis/src/registry.ts | 8 +- vendor/cordis/src/service.ts | 56 +++++---- vendor/cordis/src/utils.ts | 11 +- vendor/include/src/index.ts | 2 +- vendor/loader/src/index.ts | 6 +- 51 files changed, 731 insertions(+), 400 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.zh.md create mode 100644 scripts/cordis-core-rc12.spec.ts diff --git a/apps/cli/tests/profiles/headless/tests/fixtures/subagent-settlement-fence.ts b/apps/cli/tests/profiles/headless/tests/fixtures/subagent-settlement-fence.ts index c2c8a87885..22c632247b 100644 --- a/apps/cli/tests/profiles/headless/tests/fixtures/subagent-settlement-fence.ts +++ b/apps/cli/tests/profiles/headless/tests/fixtures/subagent-settlement-fence.ts @@ -3,7 +3,7 @@ * @module subagent-settlement-fence */ -import type { Context } from '@deepseek-ai/cordis' +import { Context } from '@deepseek-ai/cordis' import type {} from '@deepseek-ai/dsh-agent-loop' import type {} from '@deepseek-ai/dsh-subagent' @@ -24,12 +24,12 @@ export function apply(ctx: Context): void { let hasDelivered = false ctx.effect(() => { - const disposeInbox = ctx.root.on('agent/inbox/inserted', ({ agent, message }) => { + const disposeInbox = ctx[Context.root].on('agent/inbox/inserted', ({ agent, message }) => { if (agent.session.header.parentSession !== undefined || message.source.kind !== 'subagent-settled') return hasDelivered = true delivered.resolve(undefined) }) - const disposeStep = ctx.root.on('agent/pre-step', async ({ agent, turn, step }, next) => { + const disposeStep = ctx[Context.root].on('agent/pre-step', async ({ agent, turn, step }, next) => { if (agent.session.header.parentSession === undefined && turn === 1 && step === 2 && !hasDelivered) { await delivered.promise } diff --git a/apps/web/tests/default-product-isolation.e2e.ts b/apps/web/tests/default-product-isolation.e2e.ts index 603a35753b..bc2408e853 100644 --- a/apps/web/tests/default-product-isolation.e2e.ts +++ b/apps/web/tests/default-product-isolation.e2e.ts @@ -1,7 +1,7 @@ /** Chromium acceptance of the shipped Web profile's actual Client plugin and module registries. */ -import { FiberState } from '@deepseek-ai/cordis' -import type { Context, Plugin, RegistryService } from '@deepseek-ai/cordis' +import { Context, FiberState } from '@deepseek-ai/cordis' +import type { Plugin, RegistryService } from '@deepseek-ai/cordis' import type { ClientModuleLoader, ClientModuleLoaderTarget } from '@deepseek-ai/dsh-client-modules/client' import { chromium } from 'playwright' import { hasExperimentalPackageReference } from '../../../scripts/experimental-package-policy.ts' @@ -73,7 +73,7 @@ it('activates the actual default Client registry without experimental packages', // Capture the first real root and immediately restore the registry method. prototype.plugin = function (...args: Parameters) { prototype.plugin = plugin - observation.ctx = this.ctx.root + observation.ctx = this.ctx[Context.root] return plugin.apply(this, args) } const modules = create(options) diff --git a/docs/cordis-api/context.i18n.yaml b/docs/cordis-api/context.i18n.yaml index 0a43065531..c0fa96635b 100644 --- a/docs/cordis-api/context.i18n.yaml +++ b/docs/cordis-api/context.i18n.yaml @@ -9,17 +9,14 @@ en: fc6fd9ae25b8e9e5 zh: 1a2407d299404ace /context/ctx-extend-meta: - en: 2c407cb9589b001f - zh: 70dc8650250cd4c5 + en: 18c7f34127f5c5fc + zh: fa37a391e9c49f24 /context/ctx-isolate-name-label: - en: ab77052c3bf31e2b - zh: 686ca829ea5b8170 + en: e086cbc07d463960 + zh: 7912984e036dbae9 /context/ctx-intercept-name-config: - en: 1bd1e349f5c8687d - zh: 7634b27d2c9bade4 -/context/ctx-root: - en: eb89a7f0d2bc1753 - zh: 263219126a310d3b + en: e4a9d3a55ed550fc + zh: 85ebe8f0d30770e3 /context/ctx-baseurl: en: 29c28e7558cea0ad zh: 9b591e449c1bfd72 @@ -38,21 +35,24 @@ /context/static-members: en: ceb197529207a8ed zh: 7d444c03f8be0f0d +/context/static-members/context-root: + en: ad7203bb4b3533fe + zh: 02b867b883050548 /context/static-members/context-effect: - en: 19f4aaef44a7e8eb - zh: 2179cf28a7ee3f6a + en: 6c3b77ace7d4fda3 + zh: 470c685819275d5f /context/static-members/context-filter: - en: e8ca384b9a1ea98b - zh: 82189892bf0afcb0 + en: 1c97248eeabea2d0 + zh: 08eadac6a0871429 /context/static-members/context-isolate: - en: b8673b719837ce51 - zh: 83892f9f96c3ac28 + en: 471d09c9440bf738 + zh: eecc52f4e5984dbf /context/static-members/context-intercept: - en: f3ebe6568cc9a863 - zh: bb51ab61a4e47d33 + en: 57e806faa3abfff6 + zh: 3d32af39e2019758 /context/static-members/context-is-value: - en: 7425e0ee4bc1ada7 - zh: 93dee27133ded9e0 + en: 0ef94fa412edfe17 + zh: 30b64cd2fbb2d12e /context/service-store-and-mixins: en: 9f7ca8a6a0f80512 zh: 05e8cbc30e5709fc diff --git a/docs/cordis-api/context.md b/docs/cordis-api/context.md index 453f607768..f4ab7b76c4 100644 --- a/docs/cordis-api/context.md +++ b/docs/cordis-api/context.md @@ -34,7 +34,7 @@ The child prototypally inherits every property of this context; own properties o **Returns** a child context inheriting from this one. -[Source](../../vendor/cordis/src/context.ts#L99) +[Source](../../vendor/cordis/src/context.ts#L101) ### ctx.isolate(name, label?) @@ -63,48 +63,38 @@ Below the returned context, reads and writes of the service `name` resolve again **Returns** a child context whose `name` service resolves in the new scope. -[Source](../../vendor/cordis/src/context.ts#L121) +[Source](../../vendor/cordis/src/context.ts#L123) ### ctx.intercept(name, config) ```ts cordis-catalog /** - * Add service-specific intercept config for plugins started below this + * Add service-specific intercept metadata for plugins started below this * context. * * Plugins loaded under the returned context see `config` merged into the - * service's resolved config (ancestor entries first; see - * `Service[symbols.resolveConfig]`). The parent context is not affected. + * service's resolved intercept metadata (injected metadata first, then + * ancestor intercepts; see `Service[symbols.resolveIntercept]`). The parent + * context is not affected. * - * @param name — the service name whose config to intercept. - * @param config — the intercept config to merge for that service. + * @param name — the service name whose metadata to intercept. + * @param config — the intercept metadata to merge for that service. * @returns a child context carrying the additional intercept entry. */ -intercept(name: K, config: Context[K] extends { [symbols.config]: infer T } ? T : never): this +intercept(name: K, config: Context[K] extends { [symbols.metadata]: infer T } ? T : never): this intercept(name: string, config: any): this ``` -Add service-specific intercept config for plugins started below this context. +Add service-specific intercept metadata for plugins started below this context. -Plugins loaded under the returned context see `config` merged into the service's resolved config (ancestor entries first; see `Service[symbols.resolveConfig]`). The parent context is not affected. +Plugins loaded under the returned context see `config` merged into the service's resolved intercept metadata (injected metadata first, then ancestor intercepts; see `Service[symbols.resolveIntercept]`). The parent context is not affected. -- `name` — the service name whose config to intercept. -- `config` — the intercept config to merge for that service. +- `name` — the service name whose metadata to intercept. +- `config` — the intercept metadata to merge for that service. **Returns** a child context carrying the additional intercept entry. -[Source](../../vendor/cordis/src/context.ts#L139) - -### ctx.root - -```ts cordis-catalog -/** The root context of the application (every child context shares it). @experimental */ -root: this -``` - -The root context of the application (every child context shares it). @experimental - -[Source](../../vendor/cordis/src/context.ts#L22) +[Source](../../vendor/cordis/src/context.ts#L142) ### ctx.baseUrl @@ -163,6 +153,17 @@ The plugin registry. Its methods are mixed onto `ctx` (`ctx.plugin`, `ctx.inject ## Static members +### Context.root + +```ts cordis-catalog +/** Symbol key of the root context (see the `Context[symbols.root]` property). */ +static readonly root: unique symbol +``` + +Symbol key of the root context (see the `Context[symbols.root]` property). + +[Source](../../vendor/cordis/src/context.ts#L44) + ### Context.effect ```ts cordis-catalog @@ -172,7 +173,7 @@ static readonly effect: unique symbol Symbol key under which a disposer exposes its EffectMeta diagnostics tree. -[Source](../../vendor/cordis/src/context.ts#L44) +[Source](../../vendor/cordis/src/context.ts#L46) ### Context.filter @@ -183,7 +184,7 @@ static readonly filter: unique symbol Symbol key for a context's listener filter, consulted on every event dispatch. -[Source](../../vendor/cordis/src/context.ts#L46) +[Source](../../vendor/cordis/src/context.ts#L48) ### Context.isolate @@ -194,7 +195,7 @@ static readonly isolate: unique symbol Symbol key of the isolation map (see the `Context[symbols.isolate]` property). -[Source](../../vendor/cordis/src/context.ts#L48) +[Source](../../vendor/cordis/src/context.ts#L50) ### Context.intercept @@ -205,7 +206,7 @@ static readonly intercept: unique symbol Symbol key of the intercept map (see the `Context[symbols.intercept]` property). -[Source](../../vendor/cordis/src/context.ts#L50) +[Source](../../vendor/cordis/src/context.ts#L52) ### Context.is(value) @@ -230,7 +231,7 @@ Works across realms and across multiple copies of cordis, because the brand is k **Returns** `true` if `value` is a Cordis context, narrowing its type. -[Source](../../vendor/cordis/src/context.ts#L61) +[Source](../../vendor/cordis/src/context.ts#L63) ## Service store and mixins diff --git a/docs/cordis-api/context.zh.md b/docs/cordis-api/context.zh.md index a5c7e36b4b..c923a56445 100644 --- a/docs/cordis-api/context.zh.md +++ b/docs/cordis-api/context.zh.md @@ -36,7 +36,7 @@ extend(meta = {}): this **返回**继承自当前上下文的子上下文。 -[源码](../../vendor/cordis/src/context.ts#L99) +[源码](../../vendor/cordis/src/context.ts#L101) ### ctx.isolate(name, label?) @@ -65,48 +65,38 @@ isolate(name: string, label?: symbol) **返回**一个子上下文,其 `name` 服务在新作用域中解析。 -[源码](../../vendor/cordis/src/context.ts#L121) +[源码](../../vendor/cordis/src/context.ts#L123) ### ctx.intercept(name, config) ```ts cordis-catalog /** - * Add service-specific intercept config for plugins started below this + * Add service-specific intercept metadata for plugins started below this * context. * * Plugins loaded under the returned context see `config` merged into the - * service's resolved config (ancestor entries first; see - * `Service[symbols.resolveConfig]`). The parent context is not affected. + * service's resolved intercept metadata (injected metadata first, then + * ancestor intercepts; see `Service[symbols.resolveIntercept]`). The parent + * context is not affected. * - * @param name — the service name whose config to intercept. - * @param config — the intercept config to merge for that service. + * @param name — the service name whose metadata to intercept. + * @param config — the intercept metadata to merge for that service. * @returns a child context carrying the additional intercept entry. */ -intercept(name: K, config: Context[K] extends { [symbols.config]: infer T } ? T : never): this +intercept(name: K, config: Context[K] extends { [symbols.metadata]: infer T } ? T : never): this intercept(name: string, config: any): this ``` -为在此上下文之下启动的插件添加服务专属的拦截配置。 +为在此上下文之下启动的插件添加服务专属的拦截元数据。 -在返回的上下文下加载的插件会看到 `config` 已合并到服务解析后的配置中(祖先条目在前;见 `Service[symbols.resolveConfig]`)。父上下文不受影响。 +在返回的上下文下加载的插件会看到 `config` 已合并到服务解析后的拦截元数据中(注入的元数据在前,其后是祖先上下文的拦截;见 `Service[symbols.resolveIntercept]`)。父上下文不受影响。 -- `name`:要拦截其配置的服务名称。 -- `config`:要为该服务合并的拦截配置。 +- `name`:要拦截其元数据的服务名称。 +- `config`:要为该服务合并的拦截元数据。 **返回**一个携带额外拦截条目的子上下文。 -[源码](../../vendor/cordis/src/context.ts#L139) - -### ctx.root - -```ts cordis-catalog -/** The root context of the application (every child context shares it). @experimental */ -root: this -``` - -应用的根上下文,所有子上下文均共享它。@experimental - -[源码](../../vendor/cordis/src/context.ts#L22) +[源码](../../vendor/cordis/src/context.ts#L142) ### ctx.baseUrl @@ -165,6 +155,17 @@ registry: RegistryService ## 静态成员 +### Context.root + +```ts cordis-catalog +/** Symbol key of the root context (see the `Context[symbols.root]` property). */ +static readonly root: unique symbol +``` + +根上下文的 symbol 键(见 `Context[symbols.root]` 属性)。 + +[源码](../../vendor/cordis/src/context.ts#L44) + ### Context.effect ```ts cordis-catalog @@ -174,7 +175,7 @@ static readonly effect: unique symbol 资源释放函数用于公开其 EffectMeta 诊断树的 symbol 键。 -[源码](../../vendor/cordis/src/context.ts#L44) +[源码](../../vendor/cordis/src/context.ts#L46) ### Context.filter @@ -185,7 +186,7 @@ static readonly filter: unique symbol 上下文监听器过滤器的 symbol 键,每次分派事件时都会查询该过滤器。 -[源码](../../vendor/cordis/src/context.ts#L46) +[源码](../../vendor/cordis/src/context.ts#L48) ### Context.isolate @@ -196,7 +197,7 @@ static readonly isolate: unique symbol 隔离映射的 symbol 键(见 `Context[symbols.isolate]` 属性)。 -[源码](../../vendor/cordis/src/context.ts#L48) +[源码](../../vendor/cordis/src/context.ts#L50) ### Context.intercept @@ -207,7 +208,7 @@ static readonly intercept: unique symbol 拦截映射的 symbol 键(见 `Context[symbols.intercept]` 属性)。 -[源码](../../vendor/cordis/src/context.ts#L50) +[源码](../../vendor/cordis/src/context.ts#L52) ### Context.is(value) @@ -232,7 +233,7 @@ static is(value: any): value is Context **返回** `true` 时,`value` 是 Cordis 上下文,并会收窄其类型。 -[源码](../../vendor/cordis/src/context.ts#L61) +[源码](../../vendor/cordis/src/context.ts#L63) ## 服务存储与混入 diff --git a/docs/cordis-api/fiber.i18n.yaml b/docs/cordis-api/fiber.i18n.yaml index aeba613660..61c4a795fc 100644 --- a/docs/cordis-api/fiber.i18n.yaml +++ b/docs/cordis-api/fiber.i18n.yaml @@ -9,80 +9,80 @@ en: b5b3510f4b6dd13a zh: a0c70471b6d779b5 /fiber/ctx-effect-execute-label: - en: 38bab93cf931eec1 - zh: 50fed09622da4926 + en: c3c64f4a17982e02 + zh: 556d9d0892554636 /fiber/ctx-fiber: en: a10e38bf26b4ecfe zh: 7c91817984c95c99 /fiber/the-fiber-class: - en: 31ca1205552db9ef - zh: 5fa2e5b9a7396576 + en: 0995b41083780a7f + zh: c1d6edd8c955ce73 /fiber/the-fiber-class/fiber-uid: - en: 2f0eb3658bb8497e - zh: 65d3c17ca8bd4f95 + en: 97907b9b47f628e3 + zh: afc3fd8bcf51fb06 /fiber/the-fiber-class/fiber-ctx: - en: 1b527d85759324f9 - zh: 54aa40db2705b95c + en: 8393cd12c6f87ea4 + zh: 788ec6d0567eafee /fiber/the-fiber-class/fiber-config: - en: 73b05dc38761b681 - zh: d663668f3e8fd33f + en: d24f74b8de157f3c + zh: f66c1ebcc87795ac /fiber/the-fiber-class/fiber-state: - en: eda419fecddc4dc8 - zh: 1a1b90f405cf3cbc + en: 024ffba980d93975 + zh: 4aad0bca3d30329a /fiber/the-fiber-class/fiber-dispose: - en: 43f4ad79a728a492 - zh: 71b216695d0afb22 + en: d73833a8055509c9 + zh: 1f3be8f3f4233f97 /fiber/the-fiber-class/fiber-committed: - en: 0485c9d782bf90da - zh: 74304cd05e9c0796 + en: 3bc72a323e4d548f + zh: 1c78f016d1a4f352 /fiber/the-fiber-class/fiber-provisions: - en: 1cf8235d0ca54124 - zh: 3d2e39064853165f + en: dc529104da1e8423 + zh: 021c26945c90996f /fiber/the-fiber-class/fiber-inertia: - en: 2a3b1d3bc37bf986 - zh: 83bd257ee685d38b + en: 19d756b6040508e1 + zh: ad3ad8e3d97207f9 /fiber/the-fiber-class/fiber-name: - en: cdc0677ce1d83361 - zh: a58305521a0626de + en: 0e3641a74c588380 + zh: eacf740caf8f4680 /fiber/the-fiber-class/fiber-assertactive: - en: 0c3e8008ff2d69e2 - zh: 7b454626d3e3a3b6 + en: 0f848c17287d271e + zh: 3fbe6481321dacc9 /fiber/the-fiber-class/fiber-effect-execute-label: - en: 0e905aa798ce3830 - zh: bbd0b0c537097d37 + en: 20310a727bc5dce8 + zh: 08296354bc91b457 /fiber/the-fiber-class/fiber-geteffects: - en: 729a1000bda8ee36 - zh: 5bfc19df3addab80 + en: 758fea501aa3ca1a + zh: a726b56da80bdbc7 /fiber/the-fiber-class/fiber-rawconfig: - en: 80d4007e42bd8b47 - zh: 14c11dc09c6402ce + en: 06d5cba285f2ea40 + zh: f5dea5faaefb1386 /fiber/the-fiber-class/fiber-effectiveconfig: - en: 8e9fcdcf458c8bde - zh: 36d21cafbf4f0198 + en: 15bd2af0334d92c0 + zh: 660b3421904532e6 /fiber/the-fiber-class/fiber-resolveconfig-config: - en: f8a9ca27b288bd4c - zh: 03ce360b5200fbdb + en: 4bffc7a79cad2f90 + zh: 243a9ff94e7c9a39 /fiber/the-fiber-class/fiber-await: - en: 3f228c1861466386 - zh: 43b3f3acfc3d314b + en: dce389b292d469e7 + zh: 634fa390a1f4555c /fiber/the-fiber-class/fiber-restart: - en: 152116f669f52e95 - zh: 11d3cd941ce32d88 + en: 7be06221fd6f0a12 + zh: a2416eb6c313f8ce /fiber/the-fiber-class/fiber-update-config-nosave: - en: a4f711258eb70e47 - zh: fff4d880d820de10 + en: d3b17d7ab1a3135e + zh: ba9167a3b8426036 /fiber/effect: - en: 007d5b214e8a8610 - zh: d74c26fbb1b8aeb6 + en: bf5ff8b45417829e + zh: 17b384d7375575ef /fiber/disposable: - en: 56e4218392fa7234 - zh: 8fea671180cacf6f + en: b405f69de650c34d + zh: 5dd7995aaccb5d87 /fiber/effectmeta: - en: 849aa91b8e67809f - zh: 4b31d7e2acd2a008 + en: cf8a5328f613b1d6 + zh: a4f37a82c132f0ed /fiber/cordiserror: - en: d276771958d3c05f - zh: 0141656ade938d55 + en: a32c8ed4338f6f7c + zh: 573e2a686eecf1f0 /fiber/validationerror: en: 178782124cc15210 zh: 2b226f43f48af555 diff --git a/docs/cordis-api/fiber.md b/docs/cordis-api/fiber.md index 3bfc3a00e9..e144dd53bd 100644 --- a/docs/cordis-api/fiber.md +++ b/docs/cordis-api/fiber.md @@ -34,7 +34,7 @@ Register a cleanup-aware effect on this fiber. **Returns** a disposer that tears the effect down and settles once done. -[Source](../../vendor/cordis/src/fiber.ts#L421) +[Source](../../vendor/cordis/src/fiber.ts#L443) ### ctx.fiber @@ -53,7 +53,7 @@ Runtime instance of one plugin application. A fiber tracks dependency state, raw and effective config, lifecycle effects, and cleanup for the plugin context returned by `ctx.plugin()`. -[Source](../../vendor/cordis/src/fiber.ts#L184) +[Source](../../vendor/cordis/src/fiber.ts#L214) ### fiber.uid @@ -64,7 +64,7 @@ public uid: number | null Unique id within the registry; 0 for the root fiber, `null` once disposed. -[Source](../../vendor/cordis/src/fiber.ts#L186) +[Source](../../vendor/cordis/src/fiber.ts#L216) ### fiber.ctx @@ -75,7 +75,7 @@ public readonly ctx: Context The context this fiber's plugin runs in (extends the parent context). -[Source](../../vendor/cordis/src/fiber.ts#L188) +[Source](../../vendor/cordis/src/fiber.ts#L218) ### fiber.config @@ -86,7 +86,7 @@ public config: any Raw plugin input retained for the next activation. -[Source](../../vendor/cordis/src/fiber.ts#L190) +[Source](../../vendor/cordis/src/fiber.ts#L220) ### fiber.state @@ -97,7 +97,7 @@ public state Current lifecycle state; transitions emit `internal/status`. -[Source](../../vendor/cordis/src/fiber.ts#L192) +[Source](../../vendor/cordis/src/fiber.ts#L222) ### fiber.dispose @@ -108,7 +108,7 @@ public readonly dispose: () => Promise Dispose this fiber: unload the plugin, then settle once cleanup finished. -[Source](../../vendor/cordis/src/fiber.ts#L194) +[Source](../../vendor/cordis/src/fiber.ts#L224) ### fiber.committed @@ -119,7 +119,7 @@ public committed: Readonly> | undefined Required implementations retained through dependent teardown. -[Source](../../vendor/cordis/src/fiber.ts#L196) +[Source](../../vendor/cordis/src/fiber.ts#L226) ### fiber.provisions @@ -130,7 +130,7 @@ public readonly provisions: Set Service implementations owned by this fiber, including isolated provisions. -[Source](../../vendor/cordis/src/fiber.ts#L198) +[Source](../../vendor/cordis/src/fiber.ts#L228) ### fiber.inertia @@ -141,7 +141,7 @@ public inertia: Promise | undefined The in-flight load/unload transition, if one is currently running. -[Source](../../vendor/cordis/src/fiber.ts#L200) +[Source](../../vendor/cordis/src/fiber.ts#L230) ### fiber.name @@ -152,7 +152,7 @@ get name() The plugin's display name, inherited from the nearest named ancestor, else `'root'`. -[Source](../../vendor/cordis/src/fiber.ts#L342) +[Source](../../vendor/cordis/src/fiber.ts#L364) ### fiber.assertActive() @@ -170,7 +170,7 @@ Throw if the fiber has already been disposed. **Returns** nothing when the fiber is still active. -[Source](../../vendor/cordis/src/fiber.ts#L357) +[Source](../../vendor/cordis/src/fiber.ts#L379) ### fiber.effect(execute, label?) @@ -201,7 +201,7 @@ Register a cleanup-aware effect on this fiber. **Returns** a disposer that tears the effect down and settles once done. -[Source](../../vendor/cordis/src/fiber.ts#L421) +[Source](../../vendor/cordis/src/fiber.ts#L443) ### fiber.getEffects() @@ -218,7 +218,7 @@ Return metadata for currently registered effects. **Returns** one `EffectMeta` tree per labeled live effect. -[Source](../../vendor/cordis/src/fiber.ts#L574) +[Source](../../vendor/cordis/src/fiber.ts#L596) ### fiber.rawConfig @@ -229,7 +229,7 @@ get rawConfig(): unknown Raw input retained for the next activation, without evaluating expressions or validating it. -[Source](../../vendor/cordis/src/fiber.ts#L649) +[Source](../../vendor/cordis/src/fiber.ts#L671) ### fiber.effectiveConfig @@ -244,7 +244,7 @@ get effectiveConfig(): unknown The object passed to plugin activation or the latest successful update that retained the instance. Candidate resolution does not publish it; volatile updates retain its references. Undefined before activation and readable after unload; callers requiring a live instance check `state`. -[Source](../../vendor/cordis/src/fiber.ts#L664) +[Source](../../vendor/cordis/src/fiber.ts#L686) ### fiber.resolveConfig(config) @@ -266,7 +266,7 @@ Evaluate and validate a candidate using this fiber's `internal/config` hooks and **Returns** The candidate's resolved config, retaining the schema's result identity. -[Source](../../vendor/cordis/src/fiber.ts#L676) +[Source](../../vendor/cordis/src/fiber.ts#L698) ### fiber.await() @@ -284,7 +284,7 @@ Wait for current lifecycle work and rethrow startup errors. **Returns** this fiber, once it has settled into a stable state. -[Source](../../vendor/cordis/src/fiber.ts#L754) +[Source](../../vendor/cordis/src/fiber.ts#L776) ### fiber.restart() @@ -302,7 +302,7 @@ Dispose and immediately reload this plugin with its current config. **Returns** a promise resolving once the reload settled. -[Source](../../vendor/cordis/src/fiber.ts#L768) +[Source](../../vendor/cordis/src/fiber.ts#L790) ### fiber.update(config, noSave?) @@ -324,7 +324,7 @@ Resolve a candidate, retain its raw config and apply it through the update water **Returns** The awaited update/restart result, or undefined when a synchronous listener handles it. -[Source](../../vendor/cordis/src/fiber.ts#L783) +[Source](../../vendor/cordis/src/fiber.ts#L805) ## Effect @@ -345,7 +345,7 @@ type Effect = | AsyncEffect ``` -[Source](../../vendor/cordis/src/fiber.ts#L83) +[Source](../../vendor/cordis/src/fiber.ts#L113) ## Disposable @@ -363,7 +363,7 @@ Disposers run in reverse registration order when the owning fiber unloads; they type Disposable = () => T ``` -[Source](../../vendor/cordis/src/fiber.ts#L74) +[Source](../../vendor/cordis/src/fiber.ts#L104) ## EffectMeta @@ -379,7 +379,7 @@ interface EffectMeta { } ``` -[Source](../../vendor/cordis/src/fiber.ts#L96) +[Source](../../vendor/cordis/src/fiber.ts#L126) ## CordisError @@ -405,7 +405,7 @@ namespace CordisError { } ``` -[Source](../../vendor/cordis/src/fiber.ts#L157) +[Source](../../vendor/cordis/src/fiber.ts#L187) ## ValidationError @@ -421,7 +421,31 @@ class ValidationError extends TypeError { * * @param issues — the standard-schema issues, one message line each. */ - constructor(issues: readonly StandardSchemaV1.Issue[]) + constructor(public issues: readonly StandardSchemaV1.Issue[]) + + /** + * Test whether a value is a config `ValidationError`, including one from another copy of Cordis. + * + * @param error — the value to test. + * @returns `true` if `error` carries the global validation-error brand. + */ + static is(error: unknown): error is ValidationError + + /** + * Convert an issue path to plain property keys. + * + * @param path — the standard-schema issue path; segments may be `{ key }` objects. + * @returns the property keys, or an empty array when the issue has no path. + */ + static normalizePath(path: StandardSchemaV1.Issue['path'] = []) + + /** + * Format an issue path as a dotted string. + * + * @param path — the standard-schema issue path. + * @returns the keys joined with `.`. + */ + static formatPath(path: StandardSchemaV1.Issue['path']) } ``` diff --git a/docs/cordis-api/fiber.zh.md b/docs/cordis-api/fiber.zh.md index 88d253452d..5dc9f12a28 100644 --- a/docs/cordis-api/fiber.zh.md +++ b/docs/cordis-api/fiber.zh.md @@ -36,7 +36,7 @@ effect(execute: () => Effect, label?: string): AsyncDisposable> **返回**一个用于撤销该作用的清理函数,并在清理完成后结算。 -[源码](../../vendor/cordis/src/fiber.ts#L421) +[源码](../../vendor/cordis/src/fiber.ts#L443) ### ctx.fiber @@ -55,7 +55,7 @@ fiber: Fiber fiber 会跟踪 `ctx.plugin()` 返回的插件上下文所对应的依赖状态、原始配置与有效配置、生命周期作用和清理操作。 -[源码](../../vendor/cordis/src/fiber.ts#L184) +[源码](../../vendor/cordis/src/fiber.ts#L214) ### fiber.uid @@ -66,7 +66,7 @@ public uid: number | null 在注册表中的唯一 id;根 fiber 的 id 为 0,dispose 后为 `null`。 -[源码](../../vendor/cordis/src/fiber.ts#L186) +[源码](../../vendor/cordis/src/fiber.ts#L216) ### fiber.ctx @@ -77,7 +77,7 @@ public readonly ctx: Context 此 fiber 的插件运行所在的上下文(扩展自父上下文)。 -[源码](../../vendor/cordis/src/fiber.ts#L188) +[源码](../../vendor/cordis/src/fiber.ts#L218) ### fiber.config @@ -88,7 +88,7 @@ public config: any 为下次激活保留的原始插件输入。 -[源码](../../vendor/cordis/src/fiber.ts#L190) +[源码](../../vendor/cordis/src/fiber.ts#L220) ### fiber.state @@ -99,7 +99,7 @@ public state 当前生命周期状态;状态转换会发出 `internal/status`。 -[源码](../../vendor/cordis/src/fiber.ts#L192) +[源码](../../vendor/cordis/src/fiber.ts#L222) ### fiber.dispose @@ -110,7 +110,7 @@ public readonly dispose: () => Promise dispose 此 fiber:卸载插件,并在清理完成后结算。 -[源码](../../vendor/cordis/src/fiber.ts#L194) +[源码](../../vendor/cordis/src/fiber.ts#L224) ### fiber.committed @@ -121,7 +121,7 @@ public committed: Readonly> | undefined 在依赖方清理完成前保留的所需服务实现。 -[源码](../../vendor/cordis/src/fiber.ts#L196) +[源码](../../vendor/cordis/src/fiber.ts#L226) ### fiber.provisions @@ -132,7 +132,7 @@ public readonly provisions: Set 此 fiber 拥有的服务实现,包括隔离域中的服务。 -[源码](../../vendor/cordis/src/fiber.ts#L198) +[源码](../../vendor/cordis/src/fiber.ts#L228) ### fiber.inertia @@ -143,7 +143,7 @@ public inertia: Promise | undefined 当前正在进行的加载或卸载转换;如果没有此类转换,则为 undefined。 -[源码](../../vendor/cordis/src/fiber.ts#L200) +[源码](../../vendor/cordis/src/fiber.ts#L230) ### fiber.name @@ -154,7 +154,7 @@ get name() 插件的显示名称,继承自最近的具名祖先;如果不存在,则为 `'root'`。 -[源码](../../vendor/cordis/src/fiber.ts#L342) +[源码](../../vendor/cordis/src/fiber.ts#L364) ### fiber.assertActive() @@ -172,7 +172,7 @@ assertActive() **返回**:fiber 仍处于活动状态时不返回任何内容。 -[源码](../../vendor/cordis/src/fiber.ts#L357) +[源码](../../vendor/cordis/src/fiber.ts#L379) ### fiber.effect(execute, label?) @@ -203,7 +203,7 @@ effect(execute: () => Effect, label?: string): AsyncDisposable> **返回**一个用于撤销该作用的清理函数,并在清理完成后结算。 -[源码](../../vendor/cordis/src/fiber.ts#L421) +[源码](../../vendor/cordis/src/fiber.ts#L443) ### fiber.getEffects() @@ -220,7 +220,7 @@ getEffects() **返回**:每个带标签的活动作用对应一棵 `EffectMeta` 树。 -[源码](../../vendor/cordis/src/fiber.ts#L574) +[源码](../../vendor/cordis/src/fiber.ts#L596) ### fiber.rawConfig @@ -232,7 +232,7 @@ get rawConfig(): unknown 保留供下次激活使用的原始输入,不执行表达式求值或验证。 -[源码](../../vendor/cordis/src/fiber.ts#L649) +[源码](../../vendor/cordis/src/fiber.ts#L671) ### fiber.effectiveConfig @@ -247,7 +247,7 @@ get effectiveConfig(): unknown 传给插件激活过程或最近一次成功保留实例的更新的对象。候选配置求值不发布结果;volatile 更新保留其中的引用。激活前为 undefined,卸载后仍可读取;需要运行中实例的调用方还应检查 `state`。 -[源码](../../vendor/cordis/src/fiber.ts#L664) +[源码](../../vendor/cordis/src/fiber.ts#L686) ### fiber.resolveConfig(config) @@ -270,7 +270,7 @@ resolveConfig(config: unknown): unknown **返回**候选配置的解析结果,保留 schema 返回对象的身份。 -[源码](../../vendor/cordis/src/fiber.ts#L676) +[源码](../../vendor/cordis/src/fiber.ts#L698) ### fiber.await() @@ -288,7 +288,7 @@ async await() **返回**:进入稳定状态后的此 fiber。 -[源码](../../vendor/cordis/src/fiber.ts#L754) +[源码](../../vendor/cordis/src/fiber.ts#L776) ### fiber.restart() @@ -306,7 +306,7 @@ dispose 此插件,并立即使用其当前配置重新加载。 **返回**一个在重新加载完成后兑现的 promise。 -[源码](../../vendor/cordis/src/fiber.ts#L768) +[源码](../../vendor/cordis/src/fiber.ts#L790) ### fiber.update(config, noSave?) @@ -328,7 +328,7 @@ update(config: any, noSave = false): Awaitable **返回** 可等待的更新或重启结果;同步监听器处理更新时为 undefined。 -[源码](../../vendor/cordis/src/fiber.ts#L783) +[源码](../../vendor/cordis/src/fiber.ts#L805) ## Effect @@ -349,7 +349,7 @@ type Effect = | AsyncEffect ``` -[源码](../../vendor/cordis/src/fiber.ts#L83) +[源码](../../vendor/cordis/src/fiber.ts#L113) ## Disposable @@ -367,7 +367,7 @@ type Effect = type Disposable = () => T ``` -[源码](../../vendor/cordis/src/fiber.ts#L74) +[源码](../../vendor/cordis/src/fiber.ts#L104) ## EffectMeta @@ -383,7 +383,7 @@ interface EffectMeta { } ``` -[源码](../../vendor/cordis/src/fiber.ts#L96) +[源码](../../vendor/cordis/src/fiber.ts#L126) ## CordisError @@ -409,7 +409,7 @@ namespace CordisError { } ``` -[源码](../../vendor/cordis/src/fiber.ts#L157) +[源码](../../vendor/cordis/src/fiber.ts#L187) ## ValidationError @@ -425,7 +425,31 @@ class ValidationError extends TypeError { * * @param issues — the standard-schema issues, one message line each. */ - constructor(issues: readonly StandardSchemaV1.Issue[]) + constructor(public issues: readonly StandardSchemaV1.Issue[]) + + /** + * Test whether a value is a config `ValidationError`, including one from another copy of Cordis. + * + * @param error — the value to test. + * @returns `true` if `error` carries the global validation-error brand. + */ + static is(error: unknown): error is ValidationError + + /** + * Convert an issue path to plain property keys. + * + * @param path — the standard-schema issue path; segments may be `{ key }` objects. + * @returns the property keys, or an empty array when the issue has no path. + */ + static normalizePath(path: StandardSchemaV1.Issue['path'] = []) + + /** + * Format an issue path as a dotted string. + * + * @param path — the standard-schema issue path. + * @returns the keys joined with `.`. + */ + static formatPath(path: StandardSchemaV1.Issue['path']) } ``` diff --git a/docs/cordis-api/inherited.md b/docs/cordis-api/inherited.md index c414eaedd5..25a2177024 100644 --- a/docs/cordis-api/inherited.md +++ b/docs/cordis-api/inherited.md @@ -15,7 +15,7 @@ This file is GENERATED from source (`scripts/gen-cordis-catalog.ts`) and verifie - `ctx.effect` — Register a disposable side effect tied to the fiber. ([`vendor/cordis/src/fiber.ts:9`](../../vendor/cordis/src/fiber.ts)) - `ctx.get / ctx.set / ctx.provide / ctx.accessor / ctx.mixin` — Low-level service-store access and binding. ([`vendor/cordis/src/reflect.ts:7`](../../vendor/cordis/src/reflect.ts)) - `ctx.extend / ctx.isolate / ctx.intercept` — Derive a child context (scoped services / isolation / interception). ([`vendor/cordis/src/context.ts:42`](../../vendor/cordis/src/context.ts)) -- `ctx.root / ctx.fiber / ctx.registry / ctx.reflect / ctx.events / ctx.logger` — Ambient handles onto the running context graph. ([`vendor/cordis/src/context.ts:16`](../../vendor/cordis/src/context.ts)) +- `ctx[Context.root] / ctx.fiber / ctx.registry / ctx.reflect / ctx.events / ctx.logger` — Ambient handles onto the running context graph. ([`vendor/cordis/src/context.ts:16`](../../vendor/cordis/src/context.ts)) - `ctx.timer (+ interval / timeout / throttle / debounce)` — Disposable timer helpers. The `timer` key is provided at runtime; the four supported helpers are mixed onto ctx directly (declared via Pick). ([`vendor/timer/src/index.ts:4`](../../vendor/timer/src/index.ts)) - `ctx.loader` — The config Loader that booted the app (present under the loader). ([`vendor/loader/src/index.ts:30`](../../vendor/loader/src/index.ts)) diff --git a/docs/cordis-api/service.i18n.yaml b/docs/cordis-api/service.i18n.yaml index f1c4076c35..66de719bd9 100644 --- a/docs/cordis-api/service.i18n.yaml +++ b/docs/cordis-api/service.i18n.yaml @@ -6,32 +6,35 @@ en: d2c0c5bce430d1be zh: 124ab2656ea6d044 /service: - en: a163fe605c4a8045 - zh: 060a6f4ce086c5c2 + en: 7a6f25d41ad5192b + zh: 2792165d3c31015e /service/service-name: - en: 32a75e66b17c0b79 - zh: 0a5ff9fc45b3bea0 + en: 1bd1a435be60580f + zh: cb8b96113cac2ed8 /service/static-members: en: ceb197529207a8ed zh: 7d444c03f8be0f0d /service/static-members/service-init: - en: ade1a1c4543fac8c - zh: b7a4b616ee930b5b + en: a0740625ccc443b1 + zh: 1efa474f255783ee /service/static-members/service-check: - en: 111351ada5972a9a - zh: 1537da7793a6a02c -/service/static-members/service-config: - en: 93d8ff69722f9b46 - zh: 9ba1532d164c2231 + en: 699de9371410a4c0 + zh: 32343701e1c3fb5a /service/static-members/service-invoke: - en: 6d87f35f8cf52b05 - zh: 278dbce6025b2834 + en: 24ec894223f0958f + zh: 81b7615fc897f318 +/service/static-members/service-metadata: + en: 735840e221643d61 + zh: 1c2ce2f18786e0c6 /service/static-members/service-extend: - en: 5b78b68d8de8cef9 - zh: 6df27f37da11a104 + en: fa797364cccc8cc3 + zh: 8fa77ae99efee25e /service/static-members/service-tracker: - en: 52071ebded7ec026 - zh: 4647fa3f989b5deb -/service/static-members/service-resolveconfig: - en: ad62f59468d1a765 - zh: 4a31b52f61e1af6e + en: f59cdcca1f9b972a + zh: b50793b1114cff35 +/service/static-members/service-mergeintercept: + en: af31055b96f4834f + zh: 27b22f17ba6329c0 +/service/static-members/service-resolveintercept: + en: 72a73af9a6c877db + zh: 41cf10059ebf51ee diff --git a/docs/cordis-api/service.md b/docs/cordis-api/service.md index d4b0f06da1..0c1bb25449 100644 --- a/docs/cordis-api/service.md +++ b/docs/cordis-api/service.md @@ -9,7 +9,7 @@ Base class for services that expose a named API on `ctx`. Subclasses call `super(ctx, name)` from their constructor. The service is registered immediately and is automatically removed with the owning fiber. -[Source](../../vendor/cordis/src/service.ts#L11) +[Source](../../vendor/cordis/src/service.ts#L12) ### service.name @@ -20,7 +20,7 @@ public name!: string The service name this instance is registered under. -[Source](../../vendor/cordis/src/service.ts#L30) +[Source](../../vendor/cordis/src/service.ts#L33) ## Static members @@ -33,7 +33,7 @@ static readonly init: unique symbol Symbol key of an instance method run after construction (class plugins). -[Source](../../vendor/cordis/src/service.ts#L13) +[Source](../../vendor/cordis/src/service.ts#L14) ### Service.check @@ -44,18 +44,7 @@ static readonly check: unique symbol Symbol key of the availability predicate passed to `ctx.provide()`. -[Source](../../vendor/cordis/src/service.ts#L15) - -### Service.config - -```ts cordis-catalog -/** Symbol key of the phantom intercept-config type parameter. */ -static readonly config: unique symbol -``` - -Symbol key of the phantom intercept-config type parameter. - -[Source](../../vendor/cordis/src/service.ts#L17) +[Source](../../vendor/cordis/src/service.ts#L16) ### Service.invoke @@ -66,7 +55,18 @@ static readonly invoke: unique symbol Symbol key of the call body making a service callable (e.g. `ctx.logger()`). -[Source](../../vendor/cordis/src/service.ts#L19) +[Source](../../vendor/cordis/src/service.ts#L18) + +### Service.metadata + +```ts cordis-catalog +/** Symbol key of the phantom intercept-metadata type parameter. */ +static readonly metadata: unique symbol +``` + +Symbol key of the phantom intercept-metadata type parameter. + +[Source](../../vendor/cordis/src/service.ts#L20) ### Service.extend @@ -77,7 +77,7 @@ static readonly extend: unique symbol Symbol key of the helper deriving an extended service instance. -[Source](../../vendor/cordis/src/service.ts#L21) +[Source](../../vendor/cordis/src/service.ts#L22) ### Service.tracker @@ -88,15 +88,26 @@ static readonly tracker: unique symbol Symbol key of the tracker metadata used for context tracing. -[Source](../../vendor/cordis/src/service.ts#L23) +[Source](../../vendor/cordis/src/service.ts#L24) -### Service.resolveConfig +### Service.mergeIntercept ```ts cordis-catalog -/** Symbol key of the intercept-config resolution helper below. */ -static readonly resolveConfig: unique symbol +/** Symbol key of the intercept-metadata merge hook below. */ +static readonly mergeIntercept: unique symbol ``` -Symbol key of the intercept-config resolution helper below. +Symbol key of the intercept-metadata merge hook below. -[Source](../../vendor/cordis/src/service.ts#L25) +[Source](../../vendor/cordis/src/service.ts#L26) + +### Service.resolveIntercept + +```ts cordis-catalog +/** Symbol key of the intercept-metadata resolution helper below. */ +static readonly resolveIntercept: unique symbol +``` + +Symbol key of the intercept-metadata resolution helper below. + +[Source](../../vendor/cordis/src/service.ts#L28) diff --git a/docs/cordis-api/service.zh.md b/docs/cordis-api/service.zh.md index ec0b443a0e..630f8bb7fb 100644 --- a/docs/cordis-api/service.zh.md +++ b/docs/cordis-api/service.zh.md @@ -11,7 +11,7 @@ 子类在构造函数中调用 `super(ctx, name)`。服务会立即注册,并随所属 fiber 自动移除。 -[源码](../../vendor/cordis/src/service.ts#L11) +[源码](../../vendor/cordis/src/service.ts#L12) ### service.name @@ -22,7 +22,7 @@ public name!: string 此实例注册时使用的服务名称。 -[源码](../../vendor/cordis/src/service.ts#L30) +[源码](../../vendor/cordis/src/service.ts#L33) ## 静态成员 @@ -35,7 +35,7 @@ static readonly init: unique symbol 构造完成后运行的实例方法所使用的符号键(类插件)。 -[源码](../../vendor/cordis/src/service.ts#L13) +[源码](../../vendor/cordis/src/service.ts#L14) ### Service.check @@ -46,18 +46,7 @@ static readonly check: unique symbol 传给 `ctx.provide()` 的可用性谓词所使用的符号键。 -[源码](../../vendor/cordis/src/service.ts#L15) - -### Service.config - -```ts cordis-catalog -/** Symbol key of the phantom intercept-config type parameter. */ -static readonly config: unique symbol -``` - -虚设拦截配置类型参数所使用的符号键。 - -[源码](../../vendor/cordis/src/service.ts#L17) +[源码](../../vendor/cordis/src/service.ts#L16) ### Service.invoke @@ -68,7 +57,18 @@ static readonly invoke: unique symbol 使服务可被调用的调用体所使用的符号键(例如 `ctx.logger()`)。 -[源码](../../vendor/cordis/src/service.ts#L19) +[源码](../../vendor/cordis/src/service.ts#L18) + +### Service.metadata + +```ts cordis-catalog +/** Symbol key of the phantom intercept-metadata type parameter. */ +static readonly metadata: unique symbol +``` + +虚设拦截元数据类型参数所使用的符号键。 + +[源码](../../vendor/cordis/src/service.ts#L20) ### Service.extend @@ -79,7 +79,7 @@ static readonly extend: unique symbol 用于派生扩展服务实例的辅助方法所使用的符号键。 -[源码](../../vendor/cordis/src/service.ts#L21) +[源码](../../vendor/cordis/src/service.ts#L22) ### Service.tracker @@ -90,15 +90,26 @@ static readonly tracker: unique symbol 上下文追踪所用跟踪器元数据的符号键。 -[源码](../../vendor/cordis/src/service.ts#L23) +[源码](../../vendor/cordis/src/service.ts#L24) -### Service.resolveConfig +### Service.mergeIntercept ```ts cordis-catalog -/** Symbol key of the intercept-config resolution helper below. */ -static readonly resolveConfig: unique symbol +/** Symbol key of the intercept-metadata merge hook below. */ +static readonly mergeIntercept: unique symbol ``` -下述拦截配置解析辅助方法所使用的符号键。 +下述拦截元数据合并钩子所使用的符号键。 -[源码](../../vendor/cordis/src/service.ts#L25) +[源码](../../vendor/cordis/src/service.ts#L26) + +### Service.resolveIntercept + +```ts cordis-catalog +/** Symbol key of the intercept-metadata resolution helper below. */ +static readonly resolveIntercept: unique symbol +``` + +下述拦截元数据解析辅助方法所使用的符号键。 + +[源码](../../vendor/cordis/src/service.ts#L28) diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.i18n.yaml new file mode 100644 index 0000000000..f43d1ca56e --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.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 docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.md +/: + en: 4de1e21e06e1c67a + zh: f3195026d93e8127 +/ctx-context-root-replaces-ctx-root-and-service-intercept-metadata-is-renamed: + en: 546ad75e75ee931f + zh: 16cd20c00e92e6f5 +/ctx-context-root-replaces-ctx-root-and-service-intercept-metadata-is-renamed/change: + en: 73b1b7e0bdffb92b + zh: 108e4d9d0d333c36 +/ctx-context-root-replaces-ctx-root-and-service-intercept-metadata-is-renamed/migration: + en: 6080606517656f7e + zh: 1e045b715c3c4946 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.md new file mode 100644 index 0000000000..13d7749096 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.md @@ -0,0 +1,29 @@ +--- +kind: upgrade-guide +description: "Cordis 4.0.0-rc.12 replaces ctx.root with ctx[Context.root] and renames the service intercept-metadata API." +--- + +# `ctx[Context.root]` replaces `ctx.root`, and service intercept metadata is renamed + +English | [中文](guide.zh.md) + +## Change + +`@deepseek-ai/cordis` now carries upstream Cordis 4.0.0-rc.12. Third-party plugins and services written against the previous release are affected: + +- `ctx.root` no longer exists. The root context is `ctx[Context.root]`; `Context.root` is a symbol exported on the `Context` class. Inside a plugin, reading `ctx.root` throws `cannot get property "root" without inject`. +- `Service.config` becomes `Service.metadata`. A service declares its intercept type with `declare [Service.metadata]: T`. +- `[Service.resolveConfig](base?, head?)` becomes `[Service.resolveIntercept]()`, which takes no arguments. +- A service's `Config.merge` hook is no longer called. Override `[Service.mergeIntercept](...values)` instead; it receives the values in increasing precedence. +- Metadata a plugin declares in object-form `inject` now has the lowest precedence. Intercepts added with `ctx.intercept()` override it; previously the injected value overrode them. +- A context created with `ctx.isolate(name)` no longer falls back to the enclosing plugin's injected `name`. Plugins started under it, and reads after its own provision is withdrawn, throw `cannot get property "" without inject`. +- A failed `ctx.parallel()` throws an `AggregateError` whose message names the event, and a fiber disposed while it was not active, such as a failed one, now settles to `FiberState.DISPOSED`. + +## Migration + +1. Replace every `ctx.root` with `ctx[Context.root]`, importing `Context` as a value from `@deepseek-ai/cordis`. Plain JavaScript without the import can read `ctx[Symbol.for('cordis.root')]`. +2. In service classes, rename `declare [Service.config]` to `declare [Service.metadata]` and calls of `[Service.resolveConfig]()` to `[Service.resolveIntercept]()`. Replace `base` and `head` arguments by declaring the base value in `inject` and adding the override with `ctx.intercept()`. +3. Move a `Config.merge` implementation to a `[Service.mergeIntercept](...values)` method on the service class. +4. Where a plugin relied on its `inject` metadata overriding an ancestor `ctx.intercept()`, set the value with `ctx.intercept()` at the plugin's context instead. +5. Where code under `ctx.isolate(name)` needs the enclosing plugin's service, provide that service inside the isolated context or start the code from a context that is not isolated. +6. Run your TypeScript build: references to `ctx.root`, `Service.config` and `Service.resolveConfig` fail to compile. Start the plugin and confirm that services resolve and logs keep their names. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.zh.md new file mode 100644 index 0000000000..981929b671 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.zh.md @@ -0,0 +1,29 @@ +--- +kind: upgrade-guide +description: "Cordis 4.0.0-rc.12 用 ctx[Context.root] 取代 ctx.root,并重命名服务拦截元数据 API。" +--- + +# `ctx[Context.root]` 取代 `ctx.root`,服务拦截元数据 API 重命名 + +[English](guide.md) | 中文 + +## 变更 + +`@deepseek-ai/cordis` 现在包含上游 Cordis 4.0.0-rc.12。针对上一版本编写的第三方插件和服务会受到以下影响: + +- `ctx.root` 不再存在。根上下文改为 `ctx[Context.root]`;`Context.root` 是 `Context` 类上导出的 symbol。在插件内读取 `ctx.root` 会抛出 `cannot get property "root" without inject`。 +- `Service.config` 改为 `Service.metadata`。服务用 `declare [Service.metadata]: T` 声明其拦截类型。 +- `[Service.resolveConfig](base?, head?)` 改为不带参数的 `[Service.resolveIntercept]()`。 +- 服务的 `Config.merge` 钩子不再被调用。改为重写 `[Service.mergeIntercept](...values)`;它按优先级从低到高接收各个值。 +- 插件在对象形式的 `inject` 中声明的元数据现在优先级最低,用 `ctx.intercept()` 添加的拦截会覆盖它;此前是注入的值覆盖拦截。 +- 用 `ctx.isolate(name)` 创建的上下文不再回退到外层插件注入的 `name`。在其下启动的插件,以及在其自身提供撤回后的读取,都会抛出 `cannot get property "" without inject`。 +- `ctx.parallel()` 失败时抛出的 `AggregateError` 的消息会注明事件名;在非活动状态下被销毁的 fiber(例如失败的 fiber)现在会进入 `FiberState.DISPOSED`。 + +## 迁移 + +1. 将所有 `ctx.root` 替换为 `ctx[Context.root]`,并从 `@deepseek-ai/cordis` 以值的形式导入 `Context`。无法导入的纯 JavaScript 可以读取 `ctx[Symbol.for('cordis.root')]`。 +2. 在服务类中,将 `declare [Service.config]` 改为 `declare [Service.metadata]`,将对 `[Service.resolveConfig]()` 的调用改为 `[Service.resolveIntercept]()`。原来的 `base` 参数改为在 `inject` 中声明,`head` 参数改为用 `ctx.intercept()` 添加。 +3. 将 `Config.merge` 的实现移到服务类的 `[Service.mergeIntercept](...values)` 方法中。 +4. 如果插件依赖其 `inject` 元数据覆盖祖先的 `ctx.intercept()`,改为在该插件的上下文上用 `ctx.intercept()` 设置该值。 +5. 如果 `ctx.isolate(name)` 之下的代码需要外层插件的服务,在隔离的上下文中提供该服务,或从未隔离的上下文启动这段代码。 +6. 运行 TypeScript 构建:引用 `ctx.root`、`Service.config` 和 `Service.resolveConfig` 的代码会编译失败。启动插件,确认服务可以解析,日志名称保持不变。 diff --git a/packages/api/gateway/tests/peer.ts b/packages/api/gateway/tests/peer.ts index 2571e791d5..ae59067b02 100644 --- a/packages/api/gateway/tests/peer.ts +++ b/packages/api/gateway/tests/peer.ts @@ -1,5 +1,5 @@ /** Owner Peers for Gateway specs: every in-process call names its Peer explicitly. */ -import type { Context } from '@deepseek-ai/cordis' +import { Context } from '@deepseek-ai/cordis' import { Peer } from '@deepseek-ai/dsh-client-connection' import type { PeerScope, Principal } from '@deepseek-ai/dsh-typert-protocol' @@ -11,10 +11,10 @@ const owners = new WeakMap() * @returns the tree's shared owner Peer. */ export function ownerPeer(ctx: Context): PeerScope { - let peer = owners.get(ctx.root) + let peer = owners.get(ctx[Context.root]) if (peer === undefined) { - peer = new Peer(ctx.root, { principal: { kind: 'owner' } }) - owners.set(ctx.root, peer) + peer = new Peer(ctx[Context.root], { principal: { kind: 'owner' } }) + owners.set(ctx[Context.root], peer) } return peer } @@ -26,5 +26,5 @@ export function ownerPeer(ctx: Context): PeerScope { * @returns an independent Peer. */ export function peerFor(ctx: Context, principal: Principal): PeerScope { - return new Peer(ctx.root, { principal }) + return new Peer(ctx[Context.root], { principal }) } diff --git a/packages/api/session-controller/tests/transport.host.spec.ts b/packages/api/session-controller/tests/transport.host.spec.ts index 8a3df2ae43..34f92153af 100644 --- a/packages/api/session-controller/tests/transport.host.spec.ts +++ b/packages/api/session-controller/tests/transport.host.spec.ts @@ -85,7 +85,7 @@ function controllers( history: HistoryController web: WebController } { - roots.add(ctx.root) + roots.add(ctx[Context.root]) installSessionReadTestServices(ctx) const history = new HistoryController(ctx) return { history, web: new WebController(ctx, history, promote) } diff --git a/packages/boot/app-boot/tests/app-boot.spec.ts b/packages/boot/app-boot/tests/app-boot.spec.ts index 48f2e4456c..3903c15fd2 100644 --- a/packages/boot/app-boot/tests/app-boot.spec.ts +++ b/packages/boot/app-boot/tests/app-boot.spec.ts @@ -1054,7 +1054,7 @@ describe('boot', () => { writeFileSync(join(dir, 'exiting.mjs'), [ 'export const name = "exiting"', 'export function apply(ctx) {', - ' void ctx.root.fiber.dispose()', + ' void ctx[Symbol.for("cordis.root")].fiber.dispose()', '}', '', ].join('\n')) diff --git a/packages/boot/app-boot/tests/config-reload.spec.ts b/packages/boot/app-boot/tests/config-reload.spec.ts index f96ddd36c6..c0d10e30db 100644 --- a/packages/boot/app-boot/tests/config-reload.spec.ts +++ b/packages/boot/app-boot/tests/config-reload.spec.ts @@ -293,7 +293,7 @@ describe('shipped builtins', () => { // implementation is stored under that symbol, so the root realm cannot // resolve the service and a second composition mounting the same rows // cannot collide with this one. - const rootKey = ctx.root[Context.isolate].demoRealmSvc + const rootKey = ctx[Context.root][Context.isolate].demoRealmSvc expect(rootKey).toBeDefined() expect(ctx.reflect.store[rootKey!]).toBeUndefined() } finally { diff --git a/packages/boot/config-editor/src/index.ts b/packages/boot/config-editor/src/index.ts index 8fe686e478..2cc341187c 100644 --- a/packages/boot/config-editor/src/index.ts +++ b/packages/boot/config-editor/src/index.ts @@ -93,7 +93,7 @@ export class ConfigEditor extends Service { await withFileLock(join(this.ownerContext.profileContext.dir, 'package.json'), async () => { if (!this.entries().includes(entry) || entry.fiber === undefined) throw new Error('Configuration entry is no longer available') const beforePatches = readProfilePatches('dsh', this.ownerContext.profileContext) - await reconcileProfilePatches(this.ownerContext.root, beforePatches, 'dsh') + await reconcileProfilePatches(this.ownerContext[Context.root], beforePatches, 'dsh') if (!this.entries().includes(entry)) throw new Error('Configuration entry changed during reload') const current = structuredClone((entry.options.config ?? {}) as Record) const inherited = this.inherited(entry, loadProfileDirectory('dsh', this.ownerContext.profileContext.dir, this.ownerContext.profileContext.installAnchor)) @@ -140,10 +140,10 @@ export class ConfigEditor extends Service { } await writeFileAtomic(path, String(document), { mode: 0o600 }) try { - await reconcileProfilePatches(this.ownerContext.root, patches, 'dsh', [entry.options.id]) + await reconcileProfilePatches(this.ownerContext[Context.root], patches, 'dsh', [entry.options.id]) } catch (error) { await writeFileAtomic(path, before, { mode: 0o600 }) - await reconcileProfilePatches(this.ownerContext.root, beforePatches, 'dsh') + await reconcileProfilePatches(this.ownerContext[Context.root], beforePatches, 'dsh') throw error } }) diff --git a/packages/boot/hmr/src/index.ts b/packages/boot/hmr/src/index.ts index 8c5c97070a..112732ca77 100644 --- a/packages/boot/hmr/src/index.ts +++ b/packages/boot/hmr/src/index.ts @@ -971,7 +971,7 @@ class Hmr extends Service { return job !== undefined && namespaceOf(job) === undefined })) }, undefined) - const result = await recomposeProfile(this.ownerContext.root, patches, 'dsh', { requiredIds, running }) + const result = await recomposeProfile(this.ownerContext[Context.root], patches, 'dsh', { requiredIds, running }) const restartReason = compared === undefined || unavailable ? 'module-comparison' : result.restartReason return { warnings: result.warnings, pending, ...restartReason === undefined ? {} : { restartReason } } } finally { diff --git a/packages/boot/hmr/tests/package-reload.spec.ts b/packages/boot/hmr/tests/package-reload.spec.ts index f70e85e72c..cb084b3deb 100644 --- a/packages/boot/hmr/tests/package-reload.spec.ts +++ b/packages/boot/hmr/tests/package-reload.spec.ts @@ -348,7 +348,7 @@ it('reports a stopped entry that no recomposition started again by its fiber sta f.ctx.registry.delete(plugin) await Promise.all(fibers.map(fiber => fiber.await())) // Applying the same patches leaves the unchanged Include's rows alone. - const warnings = await f.ctx.hmr.runExclusive(() => reconcileProfilePatches(f.ctx.root, readProfilePatches('test', f.profile), 'test')) + const warnings = await f.ctx.hmr.runExclusive(() => reconcileProfilePatches(f.ctx[Context.root], readProfilePatches('test', f.profile), 'test')) expect(warnings).toEqual([expect.stringMatching(/^addon \(addon\): fiber state 4/u)]) }) diff --git a/packages/bundle/web-app/src/index.ts b/packages/bundle/web-app/src/index.ts index b93b559620..052f9789f1 100644 --- a/packages/bundle/web-app/src/index.ts +++ b/packages/bundle/web-app/src/index.ts @@ -15,7 +15,7 @@ import { spawn, type ChildProcess } from 'node:child_process' import { createRequire } from 'node:module' import { dirname, join } from 'node:path' -import type { Context } from '@deepseek-ai/cordis' +import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { auditStartupEntries } from '@deepseek-ai/dsh-app-boot' import type {} from '@deepseek-ai/dsh-client-connection' @@ -223,10 +223,10 @@ export function apply(ctx: Context, config: Config): void { // route owner are still mounting. Await Loader settlement first; a // hand-built tree without a Loader is already the complete tree. const announceReady = (): void => { - if (ANNOUNCED_ROOTS.has(connectionCtx.root)) return + if (ANNOUNCED_ROOTS.has(connectionCtx[Context.root])) return const webUrl = appRootUrl() const authenticatedUrl = connectionCtx.connection.authenticatedUrl(webUrl) - ANNOUNCED_ROOTS.add(connectionCtx.root) + ANNOUNCED_ROOTS.add(connectionCtx[Context.root]) if (config.printUrl) { console.log(`dsh web: ${authenticatedUrl}`) } @@ -245,7 +245,7 @@ export function apply(ctx: Context, config: Config): void { if (settled === undefined) announceReady() else { void settled.then(async () => { - await auditStartupEntries(connectionCtx.root, 'dsh web', () => {}) + await auditStartupEntries(connectionCtx[Context.root], 'dsh web', () => {}) // The tree can be disposed while the boot was in flight (early // SIGTERM); a URL line or browser tab for a dead server would only // mislead, and reading torn-down services would turn a clean shutdown diff --git a/packages/client/connection/src/index.ts b/packages/client/connection/src/index.ts index d563cd40e8..3c3a41ab14 100644 --- a/packages/client/connection/src/index.ts +++ b/packages/client/connection/src/index.ts @@ -1,5 +1,5 @@ /** Host HTTP bridge for browser-client RPC. */ -import type { Context } from '@deepseek-ai/cordis' +import { Context } from '@deepseek-ai/cordis' import type { IncomingMessage, ServerResponse } from 'node:http' import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-attachment' @@ -136,7 +136,7 @@ export async function apply(ctx: Context, config?: ConnectionConfig): Promise { assertImageBodyCapacity(webCtx, maxRequestBodyBytes) diff --git a/packages/experimental/auto-review/src/index.ts b/packages/experimental/auto-review/src/index.ts index 29df7771f0..3513c23f66 100644 --- a/packages/experimental/auto-review/src/index.ts +++ b/packages/experimental/auto-review/src/index.ts @@ -16,7 +16,7 @@ declare module '@deepseek-ai/dsh-llm/types' { import type {} from '@deepseek-ai/dsh-tool-executor-ptc/types' import type {} from '@deepseek-ai/dsh-working-directory' -import { FiberState, type Context } from '@deepseek-ai/cordis' +import { Context, FiberState } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-agent-instructions' import { @@ -788,7 +788,7 @@ export function apply(ctx: Context): void { accepting = false try { // Root unload begins before child cleanup; only live plugin removal changes Session policy. - if (ctx.root.fiber.state === FiberState.ACTIVE) { + if (ctx[Context.root].fiber.state === FiberState.ACTIVE) { for (const session of ctx.sessions.list()) { if (permissionPresets.current(session) !== AUTO_PRESET) continue permissionPresets.set(session, 'danger-full-access') diff --git a/packages/experimental/auto-review/tests/auto-review.spec.ts b/packages/experimental/auto-review/tests/auto-review.spec.ts index 45e0b8dcb5..52cf71e35d 100644 --- a/packages/experimental/auto-review/tests/auto-review.spec.ts +++ b/packages/experimental/auto-review/tests/auto-review.spec.ts @@ -1469,7 +1469,7 @@ describe('cancellation and integration teardown', () => { await auto.restart() - expect(ctx.root.fiber.state).toBe(FiberState.ACTIVE) + expect(ctx[Context.root].fiber.state).toBe(FiberState.ACTIVE) expect(ctx.permissionPresets.current(session)).toBe('danger-full-access') expect(ctx.permissionPresets.names).toContain(AUTO_PRESET) expect(session.snapshotEvents().filter(event => event.type === 'approval/policy').at(-1)?.data) @@ -1530,7 +1530,7 @@ describe('cancellation and integration teardown', () => { const disposal = ctx.fiber.dispose().then(() => { disposed = true }) try { await cancelled.promise - expect(ctx.root.fiber.state).toBe(FiberState.UNLOADING) + expect(ctx[Context.root].fiber.state).toBe(FiberState.UNLOADING) expect(disposed).toBe(false) expect(sessions.list()).toContain(session) expect(events).toEqual(beforeShutdown) diff --git a/packages/experimental/inspector/src/shared/cordis/observer.ts b/packages/experimental/inspector/src/shared/cordis/observer.ts index 00793a3739..b220e5543b 100644 --- a/packages/experimental/inspector/src/shared/cordis/observer.ts +++ b/packages/experimental/inspector/src/shared/cordis/observer.ts @@ -1,6 +1,6 @@ /** Lifecycle-driven Cordis tree publication shared by Host and Client plugin faces. */ -import type { Context } from '@deepseek-ai/cordis' +import { Context } from '@deepseek-ai/cordis' import type { CordisTreeSnapshot } from './snapshot.ts' import { CordisTreeCollector, type CordisTreeLimits } from './collector.ts' @@ -19,7 +19,7 @@ export function observeCordisTree( listener: CordisTreeSnapshotListener, limits: CordisTreeLimits, ): () => void { - const collector = new CordisTreeCollector(ctx.root, limits) + const collector = new CordisTreeCollector(ctx[Context.root], limits) let scheduled = false let closed = false const publish = (): void => { diff --git a/packages/extensions/cordis-client-runner/src/client/api-catalog.ts b/packages/extensions/cordis-client-runner/src/client/api-catalog.ts index 1d444f3c2f..0eef4b5c7b 100644 --- a/packages/extensions/cordis-client-runner/src/client/api-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/api-catalog.ts @@ -1113,7 +1113,7 @@ export const INHERITED_CTX_API: readonly InheritedApiEntry[] = [ { name: 'ctx.effect', summary: 'Register a disposable side effect tied to the fiber.' }, { name: 'ctx.get / ctx.set / ctx.provide / ctx.accessor / ctx.mixin', summary: 'Low-level service-store access and binding.' }, { name: 'ctx.extend / ctx.isolate / ctx.intercept', summary: 'Derive a child context (scoped services / isolation / interception).' }, - { name: 'ctx.root / ctx.fiber / ctx.registry / ctx.reflect / ctx.events / ctx.logger', summary: 'Ambient handles onto the running context graph.' }, + { name: 'ctx[Context.root] / ctx.fiber / ctx.registry / ctx.reflect / ctx.events / ctx.logger', summary: 'Ambient handles onto the running context graph.' }, { name: 'ctx.timer (+ interval / timeout / throttle / debounce)', summary: 'Disposable timer helpers. The `timer` key is provided at runtime; the four supported helpers are mixed onto ctx directly (declared via Pick).' }, { name: 'ctx.loader', summary: 'The config Loader that booted the app (present under the loader).' }, ] diff --git a/packages/extensions/cordis-host-runner/tests/sandbox-context.spec.ts b/packages/extensions/cordis-host-runner/tests/sandbox-context.spec.ts index a6393512c1..c1347676a4 100644 --- a/packages/extensions/cordis-host-runner/tests/sandbox-context.spec.ts +++ b/packages/extensions/cordis-host-runner/tests/sandbox-context.spec.ts @@ -63,6 +63,21 @@ describe('sandbox context façade — escape surface is closed', () => { expect(harness.ctx.tools.get('smuggled')).toBeUndefined() }) + it('withholds the ctx[Context.root] symbol key, so the root bypass registers nothing', async () => { + const harness = await setup() + const message = await runTouching(harness, ` + ctx[Symbol.for('cordis.root')].tools.register({ + name: 'smuggled_via_root_key', + description: 'raw, unguarded', + parameters: { type: 'object', properties: {} }, + ${CONTENT_OUTPUT_CODE} + async execute() { return [] }, + }) + `) + expect(message).toContain("reading 'tools'") + expect(harness.ctx.tools.get('smuggled_via_root_key')).toBeUndefined() + }) + it('rejects assignment to the façade rather than silently dropping it', async () => { const harness = await setup() await expect(mount(harness, 'return { name: \'writer\', apply(ctx) { ctx.stash = 1 } }')) @@ -71,7 +86,7 @@ describe('sandbox context façade — escape surface is closed', () => { it('denies a service whose method returns a Context (the .ctx escape), registering nothing', async () => { // A cordis Service instance carries `.ctx` (a real Context), so - // `ctx.systemPrompt.ctx.root.tools.register(…)` would escape the façade; service-return + // `ctx.systemPrompt.ctx[Context.root].tools.register(…)` would escape the façade; service-return // guards reject that Context before the registration lands. const harness = await setup() const message = await (async (): Promise => { @@ -81,7 +96,7 @@ describe('sandbox context façade — escape surface is closed', () => { name: 'svc-ctx-escape', inject: ['systemPrompt', 'tools'], apply(ctx) { - ctx.systemPrompt.ctx.root.tools.register({ + ctx.systemPrompt.ctx[Symbol.for('cordis.root')].tools.register({ name: 'smuggled_via_service', description: 'raw, unguarded', parameters: { type: 'object', properties: {} }, diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 1bcc88ab60..734a7eeaf5 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -10506,7 +10506,7 @@ export const INHERITED_CTX_API: readonly InheritedApiEntry[] = [ { name: 'ctx.effect', summary: 'Register a disposable side effect tied to the fiber.' }, { name: 'ctx.get / ctx.set / ctx.provide / ctx.accessor / ctx.mixin', summary: 'Low-level service-store access and binding.' }, { name: 'ctx.extend / ctx.isolate / ctx.intercept', summary: 'Derive a child context (scoped services / isolation / interception).' }, - { name: 'ctx.root / ctx.fiber / ctx.registry / ctx.reflect / ctx.events / ctx.logger', summary: 'Ambient handles onto the running context graph.' }, + { name: 'ctx[Context.root] / ctx.fiber / ctx.registry / ctx.reflect / ctx.events / ctx.logger', summary: 'Ambient handles onto the running context graph.' }, { name: 'ctx.timer (+ interval / timeout / throttle / debounce)', summary: 'Disposable timer helpers. The `timer` key is provided at runtime; the four supported helpers are mixed onto ctx directly (declared via Pick).' }, { name: 'ctx.loader', summary: 'The config Loader that booted the app (present under the loader).' }, ] diff --git a/packages/mcp/mcp-client/src/index.ts b/packages/mcp/mcp-client/src/index.ts index d13119def6..016878897f 100644 --- a/packages/mcp/mcp-client/src/index.ts +++ b/packages/mcp/mcp-client/src/index.ts @@ -13,7 +13,7 @@ * @module @deepseek-ai/dsh-mcp-client */ -import type { Context, Fiber } from '@deepseek-ai/cordis' +import { Context, type Fiber } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { scopeOf } from '@deepseek-ai/dsh-scope' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' @@ -210,7 +210,7 @@ export async function apply(ctx: Context, config: Config): Promise { // Fiber and survives its reloads and final disposal. let status!: ReturnType ctx.effect(() => { - const owner = scopeOf(ctx) ?? ctx.root + const owner = scopeOf(ctx) ?? ctx[Context.root] let names = activeServerNames.get(owner) if (!names) { names = new Set() diff --git a/packages/preset/agent-preset-registry/src/mount.ts b/packages/preset/agent-preset-registry/src/mount.ts index 32c36a5e39..cffcad03b9 100644 --- a/packages/preset/agent-preset-registry/src/mount.ts +++ b/packages/preset/agent-preset-registry/src/mount.ts @@ -68,7 +68,7 @@ function withinFiber(fiber: Fiber, root: Fiber): boolean { */ export function leakedServices(ctx: Context, mount: Fiber): string[] { const store = ctx.reflect.store - const rootIsolate = ctx.root[Context.isolate] + const rootIsolate = ctx[Context.root][Context.isolate] const leaked: string[] = [] for (const key of Object.getOwnPropertySymbols(store)) { const impl = store[key] diff --git a/packages/sdk/server/src/index.ts b/packages/sdk/server/src/index.ts index 3fa3759550..974c2a122d 100644 --- a/packages/sdk/server/src/index.ts +++ b/packages/sdk/server/src/index.ts @@ -9,7 +9,7 @@ * @module @deepseek-ai/dsh-sdk-jsonrpc-server */ -import type { Context } from '@deepseek-ai/cordis' +import { Context } from '@deepseek-ai/cordis' import type { Readable, Writable } from 'node:stream' import Schema from '@deepseek-ai/schemastery' import { JsonRpcLineTransport } from '@deepseek-ai/dsh-sdk-protocol' @@ -47,7 +47,7 @@ export function apply(ctx: Context, config: JsonRpcConfig): void { const resolvedConfig = config as JsonRpcConfig & { maxTokensAsSuccess: boolean } // Protocol shutdown owns the complete runtime process, so it must await the // root lifecycle (including persistence) before exiting. - const rootFiber = ctx.root.fiber + const rootFiber = ctx[Context.root].fiber /* v8 ignore next -- production stdio wiring; tests always inject the runtime hooks */ const input = config.input ?? process.stdin /* v8 ignore next -- production stdio wiring; tests always inject the runtime hooks */ diff --git a/packages/settings/settings/src/index.ts b/packages/settings/settings/src/index.ts index 5e9a9cd59d..1fbcacce58 100644 --- a/packages/settings/settings/src/index.ts +++ b/packages/settings/settings/src/index.ts @@ -232,7 +232,7 @@ export class SettingsForms extends Service { const ctx = ownerContext ctx.effect(() => () => { this.closed = true }) ctx.on('app-boot/config-reload', () => { this.invalidate() }) - void ctx.root.loader.await().then(() => this.importLegacyDocument()).catch((error: unknown) => { ctx.logger.error(error) }) + void ctx[Context.root].loader.await().then(() => this.importLegacyDocument()).catch((error: unknown) => { ctx.logger.error(error) }) } /** Move the sections of the removed `settings.yaml` into the active profile once the Loader has settled every entry. diff --git a/packages/test-support/session-snapshot/tests/fixtures/subagent-send-message-fence.ts b/packages/test-support/session-snapshot/tests/fixtures/subagent-send-message-fence.ts index f8a931a3a5..7f0cd70f28 100644 --- a/packages/test-support/session-snapshot/tests/fixtures/subagent-send-message-fence.ts +++ b/packages/test-support/session-snapshot/tests/fixtures/subagent-send-message-fence.ts @@ -4,7 +4,7 @@ * @module subagent-send-message-fence */ -import type { Context } from '@deepseek-ai/cordis' +import { Context } from '@deepseek-ai/cordis' import type {} from '@deepseek-ai/dsh-agent-loop' /** Fixture plugin name. */ @@ -23,12 +23,12 @@ export function apply(ctx: Context): void { let parentMaintenance: Promise | undefined ctx.effect(() => { - const disposeSession = ctx.root.on('session/event', (session, event) => { + const disposeSession = ctx[Context.root].on('session/event', (session, event) => { if (session.header.parentSession !== undefined || event.type !== 'turn/end' || event.data.turn !== 1) return hasStopped = true parentStopped.resolve(undefined) }) - const disposeStatus = ctx.root.on('agent/status', ({ agent, status }) => { + const disposeStatus = ctx[Context.root].on('agent/status', ({ agent, status }) => { if ( agent.session.header.parentSession === undefined && status === 'idle' && @@ -40,7 +40,7 @@ export function apply(ctx: Context): void { }) } }) - const disposeInbox = ctx.root.on('agent/inbox/inserted', ({ agent, message }) => { + const disposeInbox = ctx[Context.root].on('agent/inbox/inserted', ({ agent, message }) => { if ( agent.session.header.parentSession === undefined && message.source.kind === 'subagent-settled' @@ -48,7 +48,7 @@ export function apply(ctx: Context): void { childSettled.resolve(undefined) } }) - const disposeStep = ctx.root.on('agent/pre-step', async ({ agent, turn, step }, next) => { + const disposeStep = ctx[Context.root].on('agent/pre-step', async ({ agent, turn, step }, next) => { if (agent.session.header.parentSession !== undefined) { childReady.resolve(undefined) if (!hasStopped) await parentStopped.promise diff --git a/packages/typert/protocol/src/index.ts b/packages/typert/protocol/src/index.ts index 7972cd5ef6..e6375e6659 100644 --- a/packages/typert/protocol/src/index.ts +++ b/packages/typert/protocol/src/index.ts @@ -270,8 +270,8 @@ export abstract class TypertRemoteService extends Service { * tree registers it on the root, where it outlives any one Service. */ function provideInvocationAccessor(ctx: Context): void { - if (Object.hasOwn(ctx.root.reflect.props, 'invocation')) return - ctx.root.accessor('invocation', { get: () => undefined }) + if (Object.hasOwn(ctx[Context.root].reflect.props, 'invocation')) return + ctx[Context.root].accessor('invocation', { get: () => undefined }) } /** diff --git a/scripts/cordis-core-api.spec.ts b/scripts/cordis-core-api.spec.ts index 8aef4041a1..8c2ace851b 100644 --- a/scripts/cordis-core-api.spec.ts +++ b/scripts/cordis-core-api.spec.ts @@ -25,7 +25,7 @@ describe('Cordis core API generation', () => { expect(pages.get('docs/cordis-api/events.md')).toContain('## DispatchMode') expect(pages.get('docs/cordis-api/fiber.md')).toContain('## EffectMeta') expect(pages.get('docs/cordis-api/registry.md')).toContain('## Plugin') - expect(pages.get('docs/cordis-api/service.md')).toContain('### Service.resolveConfig') + expect(pages.get('docs/cordis-api/service.md')).toContain('### Service.resolveIntercept') const fiber = pages.get('docs/cordis-api/fiber.md') ?? '' expect(fiber).toContain('```\n\nRegister a cleanup-aware effect on this fiber.') diff --git a/scripts/cordis-core-lifecycle.spec.ts b/scripts/cordis-core-lifecycle.spec.ts index 20f456db81..becd02fa37 100644 --- a/scripts/cordis-core-lifecycle.spec.ts +++ b/scripts/cordis-core-lifecycle.spec.ts @@ -110,7 +110,8 @@ describe('Cordis rc.11 lifecycle', () => { await isolated.plugin((child) => { expect(child.rc11View).toBe('inner') }) await withdraw() expect(owner.rc11View).toBe('outer') - expect(isolated.rc11View).toBe('outer') + // The isolated context does not fall back to the injected view once its own provision is withdrawn. + expect(() => isolated.rc11View).toThrow('without inject') }) await ctx.plugin((owner) => { owner.isolate('rc11Private').provide('rc11Private', true) diff --git a/scripts/cordis-core-rc12.spec.ts b/scripts/cordis-core-rc12.spec.ts new file mode 100644 index 0000000000..b706e8b6e3 --- /dev/null +++ b/scripts/cordis-core-rc12.spec.ts @@ -0,0 +1,114 @@ +/** Cordis rc.12 root access, intercept metadata, isolation, disposal and event errors. */ +import { Context, FiberState, Service } from '@deepseek-ai/cordis' +import { describe, expect, it, onTestFinished, vi } from 'vitest' + +interface Metadata { + a?: number + b?: number + c?: number + tags?: string[] +} + +declare module '@deepseek-ai/cordis' { + interface Context { + rc12Meta: MetadataService + rc12View: string + } +} + +class MetadataService extends Service { + constructor(ctx: Context) { + super(ctx, 'rc12Meta') + } + + read(): Metadata { + return this[Service.resolveIntercept]() + } +} + +function root() { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + return ctx +} + +describe('Cordis rc.12 core', () => { + it('exposes the root context through Context.root only', async () => { + const ctx = root() + const seen: unknown[] = [] + await ctx.plugin((child: Context) => { + seen.push(child[Context.root]) + seen.push(child[Symbol.for('cordis.root') as typeof Context.root]) + expect(() => { Reflect.get(child, 'root') }).toThrow('cannot get property "root" without inject') + }) + expect(seen).toEqual([ctx, ctx]) + }) + + it('merges injected metadata under context intercepts', async () => { + const ctx = root() + await ctx.plugin(MetadataService) + let metadata!: Metadata + await ctx.intercept('rc12Meta', { b: 2 }).inject({ rc12Meta: { a: 1, b: 1 } }, (child) => { + metadata = child.intercept('rc12Meta', { c: 3 }).rc12Meta.read() + }) + expect(metadata).toEqual({ a: 1, b: 2, c: 3 }) + }) + + it('merges through an overridden mergeIntercept in increasing precedence', async () => { + class Tagged extends MetadataService { + override [Service.mergeIntercept](...values: Metadata[]): Metadata { + return { tags: values.flatMap(value => value.tags ?? []) } + } + } + const ctx = root() + await ctx.plugin(Tagged) + let metadata!: Metadata + await ctx.intercept('rc12Meta', { tags: ['outer'] }).inject({ rc12Meta: { tags: ['inject'] } }, (child) => { + metadata = child.intercept('rc12Meta', { tags: ['inner'] }).rc12Meta.read() + }) + expect(metadata).toEqual({ tags: ['inject', 'outer', 'inner'] }) + }) + + it('does not inherit the injected view across an isolation boundary', async () => { + const ctx = root() + ctx.provide('rc12View', 'outer') + const results: string[] = [] + const read = (child: Context) => { + try { + return child.rc12View + } catch (error) { + return error instanceof Error ? error.message : String(error) + } + } + await ctx.inject(['rc12View'], async (owner) => { + await owner.plugin((child) => { results.push(read(child)) }) + await owner.isolate('rc12View').plugin((child) => { results.push(read(child)) }) + }) + expect(results).toEqual(['outer', 'cannot get property "rc12View" without inject']) + }) + + it('settles pending and failed fibers to DISPOSED', async () => { + const ctx = root() + const pending = ctx.inject(['rc12NeverProvided'], () => {}) + expect(pending.state).toBe(FiberState.PENDING) + await pending.dispose() + expect(pending.state).toBe(FiberState.DISPOSED) + + const error = vi.spyOn(ctx.logger('fiber'), 'error').mockImplementation(() => {}) + onTestFinished(() => { error.mockRestore() }) + const failed = ctx.plugin(() => { throw new Error('rc12 boom') }) + await expect(failed.await()).rejects.toThrow('rc12 boom') + expect(failed.state).toBe(FiberState.FAILED) + await failed.dispose() + expect(failed.state).toBe(FiberState.DISPOSED) + }) + + it('names the failing event in the parallel AggregateError', async () => { + const ctx = root() + ctx.on('rc12-parallel' as never, () => { throw new Error('listener failed') }) + const symbol = Symbol('rc12-symbol') + ctx.on(symbol as never, () => { throw new Error('symbol listener failed') }) + await expect(ctx.parallel('rc12-parallel' as never)).rejects.toThrow('one or more listeners of event "rc12-parallel" failed') + await expect(ctx.parallel(symbol as never)).rejects.toThrow('one or more listeners of event Symbol(rc12-symbol) failed') + }) +}) diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index dd087b3ec3..f84d4a877d 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -1193,7 +1193,7 @@ export const CORDIS_CATALOG_POLICY: CordisCatalogPolicy = { { name: 'ctx.effect', summary: 'Register a disposable side effect tied to the fiber.', source: 'vendor/cordis/src/fiber.ts:9' }, { name: 'ctx.get / ctx.set / ctx.provide / ctx.accessor / ctx.mixin', summary: 'Low-level service-store access and binding.', source: 'vendor/cordis/src/reflect.ts:7' }, { name: 'ctx.extend / ctx.isolate / ctx.intercept', summary: 'Derive a child context (scoped services / isolation / interception).', source: 'vendor/cordis/src/context.ts:42' }, - { name: 'ctx.root / ctx.fiber / ctx.registry / ctx.reflect / ctx.events / ctx.logger', summary: 'Ambient handles onto the running context graph.', source: 'vendor/cordis/src/context.ts:16' }, + { name: 'ctx[Context.root] / ctx.fiber / ctx.registry / ctx.reflect / ctx.events / ctx.logger', summary: 'Ambient handles onto the running context graph.', source: 'vendor/cordis/src/context.ts:16' }, { name: 'ctx.timer (+ interval / timeout / throttle / debounce)', summary: 'Disposable timer helpers. The `timer` key is provided at runtime; the four supported helpers are mixed onto ctx directly (declared via Pick).', source: 'vendor/timer/src/index.ts:4' }, { name: 'ctx.loader', summary: 'The config Loader that booted the app (present under the loader).', source: 'vendor/loader/src/index.ts:30' }, ], diff --git a/vendor/README.md b/vendor/README.md index 9020f5dcb6..a13f62d275 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -16,7 +16,7 @@ Upstream workspace: `cordis-workspace` (local checkout: `~/repos/cordis-workspac |---|---|---|---|---|---| | `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` | -| `cordis/` | `@deepseek-ai/cordis` | `cordis` | 4.0.0-rc.11 | https://github.com/cordiverse/cordis (`packages/core`) | `0b96d9fd517b998e44e2209560c9e5f0671ce933` | +| `cordis/` | `@deepseek-ai/cordis` | `cordis` | 4.0.0-rc.12 | https://github.com/cordiverse/cordis (`packages/core`) | `01b396240ce47cf2779c40af9bc445bb748fe112` | | `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` | @@ -30,14 +30,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. +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 V29. - **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. +- **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'`. Core's upstream source already uses explicit `.ts` specifiers. 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 · 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. `[Context.root]`), module re-exports, shared utility helpers, `EventsService`, `Fiber`, `ValidationError` and its path helpers, `RegistryService`, `ReflectService`, `Service` and its intercept-metadata members, `LoggerService` and their `declare module './context.ts'` overloads. The upstream line comment on `reflect.ts`'s exported `locate()` is rewritten as JSDoc. 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. - **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`. @@ -51,6 +51,7 @@ Keep this log exhaustive — every divergence from upstream must be listed. Each - **V25 · Loader lifecycle adaptations**: before a combined context/config update, Loader refreshes dependencies locally, which prevents activation against stale isolation bindings; disabled-entry updates await disposal. Failed fibers require an explicit update after correcting their input or dependencies. Core retains the effect hardening in V6; rc.11 owns dependency teardown ordering and superseded-activation handling. - **V26 · `loader/src/config/tree.ts` cross-tree moves**: backports [cordiverse/cordis#271](https://github.com/cordiverse/cordis/pull/271), merged after `v4.0.0-rc.11`. When `EntryTree.update()` moves an entry into a group of another tree, the entry and the same-tree members of its group move their store registrations to the target tree, and the move is rejected before either tree changes when the target tree already holds one of their ids. The source tree receives a removal and the target tree a creation, without `legacy` or `from`. In rc.11 the entry stays registered in the source tree and the target receives an update with `legacy`, so the Include journal writes a partial row and reconciling the target file creates a second Entry. Retire this entry when the vendored Loader includes the upstream fix. Covered by `scripts/cordis-include-journal.spec.ts`. - **V27 · `loader/src/config/tree.ts` explicit ids with `:`**: `ensureId()` accepts explicit ids containing `EntryTree.sep`; upstream rejects them. Generated bundles from `@deepseek-ai/dsh-creation-recommendations` prefix their row ids with `:`, and installed profiles already contain such rows. `resolve()` still splits ids on `:`, so these entries cannot be addressed by nested path. Covered by `scripts/cordis-entry-commit.spec.ts` and `packages/experimental/creation-recommendations/tests/loader-composition.spec.ts`. +- **V28 · Core rc.12 compatibility in Loader and Include**: `loader/src/index.ts` declares `[Service.metadata]`, resolves its intercept through `[Service.resolveIntercept]` and logs through `ctx[Context.root]`; `include/src/index.ts` logs through `ctx[Context.root]`. These lines match the `v4.0.0-rc.12` tag while the rest of both packages keeps its rc.11 baseline. Retire this entry when Loader and Include are synchronized to that tag. ### Resolver adaptations diff --git a/vendor/cordis/src/context.ts b/vendor/cordis/src/context.ts index b7dcf44ff6..951a0ddae4 100644 --- a/vendor/cordis/src/context.ts +++ b/vendor/cordis/src/context.ts @@ -14,12 +14,12 @@ import { Fiber } from './fiber.ts' * be read from `ctx`. */ export interface Context { + /** The root context of the application; every child context shares it. */ + [symbols.root]: this /** Isolation map: service name → scope label. Lookups for a name resolve within its label. */ [symbols.isolate]: Dict /** Intercept map: service name → config merged into that service's per-plugin config. */ [symbols.intercept]: Dict - /** The root context of the application (every child context shares it). @experimental */ - root: this /** Base URL used to resolve relative plugin/module specifiers, if the runtime sets one. */ baseUrl?: string | undefined /** The event bus. Its methods are also mixed onto `ctx` (`ctx.on`, `ctx.emit`, ...). */ @@ -40,6 +40,8 @@ export interface Context { * contexts without mutating their parent. */ export class Context { + /** Symbol key of the root context (see the `Context[symbols.root]` property). */ + static readonly root: unique symbol = symbols.root /** Symbol key under which a disposer exposes its {@link EffectMeta} diagnostics tree. */ static readonly effect: unique symbol = symbols.effect /** Symbol key for a context's listener filter, consulted on every event dispatch. */ @@ -72,7 +74,7 @@ export class Context { this[symbols.isolate] = Object.create(null) this[symbols.intercept] = Object.create(null) const self = new Proxy(this, ReflectService.handler) - this.root = self + this[symbols.root] = self this.baseUrl = undefined this.fiber = new Fiber(self, {}, Object.create(null), null, () => []) this.reflect = new ReflectService(self) @@ -125,18 +127,19 @@ export class Context { } /** - * Add service-specific intercept config for plugins started below this + * Add service-specific intercept metadata for plugins started below this * context. * * Plugins loaded under the returned context see `config` merged into the - * service's resolved config (ancestor entries first; see - * `Service[symbols.resolveConfig]`). The parent context is not affected. + * service's resolved intercept metadata (injected metadata first, then + * ancestor intercepts; see `Service[symbols.resolveIntercept]`). The parent + * context is not affected. * - * @param name — the service name whose config to intercept. - * @param config — the intercept config to merge for that service. + * @param name — the service name whose metadata to intercept. + * @param config — the intercept metadata to merge for that service. * @returns a child context carrying the additional intercept entry. */ - intercept(name: K, config: Context[K] extends { [symbols.config]: infer T } ? T : never): this + intercept(name: K, config: Context[K] extends { [symbols.metadata]: infer T } ? T : never): this intercept(name: string, config: any): this intercept(name: string, config: any) { const intercept = Object.create(this[symbols.intercept]) diff --git a/vendor/cordis/src/events.ts b/vendor/cordis/src/events.ts index 9e7b6a6633..f0dc92fbe2 100644 --- a/vendor/cordis/src/events.ts +++ b/vendor/cordis/src/events.ts @@ -166,8 +166,10 @@ export class EventsService { this.emit('internal/dispatch', type, name, args, thisArg) } const filter = thisArg?.[Context.filter] - return [thisArg, (this._hooks[name] || []) - .filter(hook => hook.global || !filter || filter.call(thisArg, hook.ctx)).map(hook => hook.callback)] as const + const callbacks = (this._hooks[name] || []) + .filter(hook => hook.global || !filter || filter.call(thisArg, hook.ctx)) + .map(hook => hook.callback) + return [thisArg, callbacks, name] as const } /** @@ -189,10 +191,12 @@ export class EventsService { * @returns a promise resolving once every listener has settled. */ async parallel(...args: any[]) { - const [thisArg, callbacks] = this._resolve('parallel', args) + const [thisArg, callbacks, name] = this._resolve('parallel', args) const results = await Promise.allSettled(callbacks.map(async callback => Reflect.apply(callback, thisArg, args))) const errors = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected') - if (errors.length) throw new AggregateError(errors.map(error => error.reason)) + if (!errors.length) return + const label = typeof name === 'symbol' ? String(name) : `"${name}"` + throw new AggregateError(errors.map(error => error.reason), `one or more listeners of event ${label} failed`) } /** diff --git a/vendor/cordis/src/fiber.ts b/vendor/cordis/src/fiber.ts index 6da19b4767..08a75215d6 100644 --- a/vendor/cordis/src/fiber.ts +++ b/vendor/cordis/src/fiber.ts @@ -24,15 +24,45 @@ export class ValidationError extends TypeError { * * @param issues — the standard-schema issues, one message line each. */ - constructor(issues: readonly StandardSchemaV1.Issue[]) { + constructor(public issues: readonly StandardSchemaV1.Issue[]) { super(`invalid config:\n` + issues.map(issue => { - if (issue.path) { - return ` - ${issue.message} (at ${issue.path.join('.')})` + if (issue.path?.length) { + return ` - ${issue.message} (at ${ValidationError.formatPath(issue.path)})` } else { return ` - ${issue.message}` } }).join('\n')) } + + /** + * Test whether a value is a config `ValidationError`, including one from another copy of Cordis. + * + * @param error — the value to test. + * @returns `true` if `error` carries the global validation-error brand. + */ + static is(error: unknown): error is ValidationError { + return !!error?.[kValidationError] + } + + /** + * Convert an issue path to plain property keys. + * + * @param path — the standard-schema issue path; segments may be `{ key }` objects. + * @returns the property keys, or an empty array when the issue has no path. + */ + static normalizePath(path: StandardSchemaV1.Issue['path'] = []) { + return path.map(segment => typeof segment === 'object' ? segment.key : segment) + } + + /** + * Format an issue path as a dotted string. + * + * @param path — the standard-schema issue path. + * @returns the keys joined with `.`. + */ + static formatPath(path: StandardSchemaV1.Issue['path']) { + return ValidationError.normalizePath(path).map(String).join('.') + } } Object.defineProperty(ValidationError.prototype, kValidationError, { @@ -239,15 +269,6 @@ export class Fiber { this.uid = parent.registry.counter this.ctx = this.context = parent.extend({ fiber: this }) - const injectEntries = Object.entries(this.inject) - if (injectEntries.length) { - this.ctx[Context.intercept] = Object.create(parent[Context.intercept]) - for (const [name, config] of injectEntries) { - if (isNullable(config)) continue - this.ctx[Context.intercept][name] = config - } - } - this._runner = { epoch: INACTIVE, getOuterStack, @@ -290,15 +311,16 @@ export class Fiber { return FiberState.UNLOADING }) } - // `this.inertia` itself should never reject — both `_reload` and - // `_unload` swallow their own work errors via `ctx.logger.error`. - // If it *does* reject, the only remaining cause is the logger - // itself failing, which we can't recover from in this exact spot - // (calling the logger again is what just failed). Let the - // rejection propagate; process-level crash is the honest outcome. + // `inertia` never rejects: `_reload` and `_unload` both log their + // own work errors. A rejection here would mean the logger itself + // failed, so let it propagate. while (this.inertia) { await this.inertia } + // `_setEpoch()` above returns early for a fiber that was not ACTIVE, + // so the cached state is not refreshed. Re-derive it now that + // `uid` is null; the empty callback falls through to `_getState()`. + this._updateState(() => {}) } }, 'ctx.plugin()') diff --git a/vendor/cordis/src/logger.ts b/vendor/cordis/src/logger.ts index 0dc97c16b3..ff35b70de5 100644 --- a/vendor/cordis/src/logger.ts +++ b/vendor/cordis/src/logger.ts @@ -1,14 +1,9 @@ import { defineProperty, hyphenate } from '@deepseek-ai/cosmokit' import { Context } from './context.ts' import { Fiber } from './fiber.ts' +import { Service } from './service.ts' import { createCallable, joinPrototype, symbols, type Tracker } from './utils.ts' -declare module './context.ts' { - interface Intercept { - logger: LoggerService.Intercept - } -} - /** Logger method name and severity category. */ export type LoggerType = 'error' | 'info' | 'warn' | 'debug' @@ -143,7 +138,9 @@ export class Logger { if (args.length === 1 && args[0] instanceof Error) { if (args[0].cause) { this[type](args[0].cause) - } else if (isAggregateError(args[0])) { + } else if (isAggregateError(args[0]) && args[0].errors.length) { + // An aggregate with no members has nothing to flatten; it is logged + // as itself, like any other error. args[0].errors.forEach(error => this[type](error)) return } @@ -192,6 +189,8 @@ export interface LoggerService extends Record { * directly to log with the current fiber-derived name. */ export class LoggerService { + declare [symbols.metadata]: LoggerService.Intercept + bufferSize = 1000 buffer: Message[] = [] ctx!: Context @@ -241,21 +240,9 @@ export class LoggerService { }, 'ctx.logger.exporter()') } - private _resolveConfig(): LoggerService.Intercept { - let intercept = this.ctx[symbols.intercept] - const configs: LoggerService.Intercept[] = [] - while ('logger' in intercept) { - if (Object.hasOwn(intercept, 'logger')) { - configs.unshift(intercept['logger']) - } - intercept = Object.getPrototypeOf(intercept) - } - return Object.assign({}, ...configs) - } - [symbols.invoke](name?: string): Logger { - const config = this._resolveConfig() const caller = (this as any)[symbols.caller] as Context | undefined + const config: LoggerService.Intercept = Service.prototype[Service.resolveIntercept].call(this) const fiber = (caller ?? this.ctx).fiber name ??= config.name name ??= hyphenate(fiber.name) diff --git a/vendor/cordis/src/reflect.ts b/vendor/cordis/src/reflect.ts index 89123616a0..c2256a3534 100644 --- a/vendor/cordis/src/reflect.ts +++ b/vendor/cordis/src/reflect.ts @@ -132,6 +132,39 @@ export interface Impl { isolate: symbol } +/** + * Resolve an access to service `name` from the def site `ctx` by walking up its fibers. + * + * - `{ impl }`: a fiber provides the impl itself in the same isolation. + * - `{ fiber, impl }`: the impl comes from the committed view of `fiber`. + * - `{ fiber }`: `fiber` declares the service but is inactive. + * - `undefined`: no fiber declares the service, or the walk reaches a context that isolates `name` again. + * + * @param ctx — the def-site context of the access. + * @param name — the service name being accessed. + * @returns the fiber whose `inject` admits the access and the impl the access reaches, or `undefined`. + */ +export function locate(ctx: Context, name: string): { fiber?: Fiber; impl?: Impl } | undefined { + const key = ctx[symbols.isolate][name] + let table = ctx[symbols.isolate] + let fiber = ctx.fiber + while (true) { + let impl: Impl | undefined + for (const provision of fiber.provisions) { + if (provision.name === name && provision.ctx[symbols.isolate][name] === key) impl = provision + } + if (impl) return { impl } + while (table !== fiber.ctx[symbols.isolate]) { + if (!table || Object.hasOwn(table, name)) return + table = Object.getPrototypeOf(table) + } + impl = fiber.committed?.[name] + if (impl || name in fiber.inject) return { fiber, impl } + if (!fiber.runtime) return + fiber = fiber.parent.fiber + } +} + /** * Reflection and service-resolution layer installed as `ctx.reflect`. * @@ -161,22 +194,11 @@ export class ReflectService { const defSite = (ctx[symbols.shadow] as Context | undefined) ?? ctx if (!defSite.fiber.runtime) return ctx.reflect.get(prop, false) return ctx.events.waterfall('internal/get', ctx, prop, error, () => { - const key = defSite[symbols.isolate][prop] - let fiber = defSite.fiber - while (true) { - let impl = fiber.committed?.[prop] - for (const provision of fiber.provisions) { - if (provision.name === prop && provision.ctx[symbols.isolate][prop] === key) impl = provision - } - if (impl) return getTraceable(ctx, impl.value) - if (prop in fiber.inject) { - error.message = `cannot get required service "${prop}" in inactive context` - throw error - } - if (!fiber.runtime) throw error - if (fiber.parent[symbols.isolate][prop] !== key) throw error - fiber = fiber.parent.fiber - } + const result = locate(defSite, prop) + if (!result) throw error + if (result.impl) return getTraceable(ctx, result.impl.value) + error.message = `cannot get required service "${prop}" in inactive context` + throw error }) } catch (e: any) { throw e === error ? enhanceError(e) : e @@ -297,7 +319,7 @@ export class ReflectService { } this.props[name] = { type: 'service' } - this.ctx.root[symbols.isolate][name] ??= Symbol(name) + this.ctx[symbols.root][symbols.isolate][name] ??= Symbol(name) const key = this.ctx[symbols.isolate][name] const impl: Impl = { uid: ++this._implCounter, name, value, ctx: this.ctx, check, isolate: key, dependents: new Set() } if (this.store[key]) { diff --git a/vendor/cordis/src/registry.ts b/vendor/cordis/src/registry.ts index 478cf036cb..fe988a2b14 100644 --- a/vendor/cordis/src/registry.ts +++ b/vendor/cordis/src/registry.ts @@ -20,7 +20,7 @@ export type Inject = (keyof M)[] | { [K in keyof M]?: M[K] } /** Context keys that correspond to services with typed intercept config. */ export type InjectKey = keyof { - [K in keyof Context & string as Context[K] extends { [symbols.config]: any } ? K : never]: any + [K in keyof Context & string as Context[K] extends { [symbols.metadata]: any } ? K : never]: any } /** @@ -31,10 +31,10 @@ export type InjectKey = keyof { */ /** * @param name — the required service name. - * @param config — optional intercept config applied for that service. + * @param config — optional intercept metadata injected for that service. * @returns the class or method decorator. */ -export function Inject(name: K, config?: Context[K] extends { [symbols.config]: infer T } ? T : never) { +export function Inject(name: K, config?: Context[K] extends { [symbols.metadata]: infer T } ? T : never) { return function (value: any, decorator: ClassDecoratorContext | ClassMethodDecoratorContext) { if (decorator.kind === 'class') { if (!Object.hasOwn(value, 'inject')) { @@ -43,7 +43,7 @@ export function Inject(name: K, config?: Context[K] extends } value.inject[name] = config } else if (decorator.kind === 'method') { - const inject = (value[symbols.metadata] ??= {}).inject ??= Object.create(null) + const inject = (value[symbols.decorator] ??= {}).inject ??= Object.create(null) inject[name] = config decorator.addInitializer(function () { const property = this[symbols.tracker]?.property diff --git a/vendor/cordis/src/service.ts b/vendor/cordis/src/service.ts index dc5742f8c2..c6ac63e30f 100644 --- a/vendor/cordis/src/service.ts +++ b/vendor/cordis/src/service.ts @@ -1,5 +1,6 @@ -import { defineProperty } from '@deepseek-ai/cosmokit' +import { defineProperty, isNullable } from '@deepseek-ai/cosmokit' import { Context } from './context.ts' +import { locate } from './reflect.ts' import { createCallable, joinPrototype, symbols, type Tracker } from './utils.ts' /** @@ -13,18 +14,20 @@ export abstract class Service { static readonly init: unique symbol = symbols.init /** Symbol key of the availability predicate passed to `ctx.provide()`. */ static readonly check: unique symbol = symbols.check - /** Symbol key of the phantom intercept-config type parameter. */ - static readonly config: unique symbol = symbols.config /** Symbol key of the call body making a service callable (e.g. `ctx.logger()`). */ static readonly invoke: unique symbol = symbols.invoke + /** Symbol key of the phantom intercept-metadata type parameter. */ + static readonly metadata: unique symbol = symbols.metadata /** Symbol key of the helper deriving an extended service instance. */ static readonly extend: unique symbol = symbols.extend /** Symbol key of the tracker metadata used for context tracing. */ static readonly tracker: unique symbol = symbols.tracker - /** Symbol key of the intercept-config resolution helper below. */ - static readonly resolveConfig: unique symbol = symbols.resolveConfig + /** Symbol key of the intercept-metadata merge hook below. */ + static readonly mergeIntercept: unique symbol = symbols.mergeIntercept + /** Symbol key of the intercept-metadata resolution helper below. */ + static readonly resolveIntercept: unique symbol = symbols.resolveIntercept - declare [symbols.config]: T + declare [symbols.metadata]: T /** The service name this instance is registered under. */ public name!: string @@ -73,32 +76,39 @@ export abstract class Service { } /** - * Merge intercept config from ancestors with optional base and head values. + * Merge intercept metadata values, lowest precedence first. * - * Entries added closer to the root apply first; `base` is prepended and - * `head` appended. Uses `Config.merge` when the service declares one, - * otherwise a shallow `Object.assign`. + * Override to customize merging; the default is a shallow `Object.assign`. * - * @param base — lowest-precedence config merged before all intercepts. - * @param head — highest-precedence config merged after all intercepts. - * @returns the merged config. + * @param values — the metadata values in increasing precedence. + * @returns the merged metadata. */ - [symbols.resolveConfig](base?: T, head?: T): T { + [symbols.mergeIntercept](...values: T[]): T { + return Object.assign({}, ...values) + } + + /** + * Resolve the intercept metadata visible to the current caller. + * + * The metadata injected by the fiber that admits the access applies first, + * then intercepts added by ancestor contexts, closest to the root first. + * The values are combined with `[Service.mergeIntercept]`. + * + * @returns the merged metadata. + */ + [symbols.resolveIntercept](): T { + const values: T[] = [] let intercept = this.ctx[Context.intercept] - const configs: any[] = [] while (this.name in intercept) { if (Object.hasOwn(intercept, this.name)) { - configs.unshift(intercept[this.name]) + values.unshift(intercept[this.name]) } intercept = Object.getPrototypeOf(intercept) } - if (base) configs.unshift(base) - if (head) configs.push(head) - if (this['Config']?.merge) { - return this['Config'].merge(...configs) - } else { - return Object.assign({}, ...configs) - } + const value = locate((this as any)[symbols.caller] ?? this.ctx, this.name)?.fiber?.inject[this.name] + if (!isNullable(value)) values.unshift(value) + const merge = this[symbols.mergeIntercept] ?? Service.prototype[symbols.mergeIntercept] + return merge.apply(this, values) } static [Symbol.hasInstance](instance: any) { diff --git a/vendor/cordis/src/utils.ts b/vendor/cordis/src/utils.ts index 07f52e6477..4337b9d6c2 100644 --- a/vendor/cordis/src/utils.ts +++ b/vendor/cordis/src/utils.ts @@ -1,5 +1,6 @@ import { defineProperty } from '@deepseek-ai/cosmokit' -import type { Context, Service } from './index.ts' +import type { Context } from './context.ts' +import type { Service } from './service.ts' /** Ordered collection of disposable values with O(1) deletion by value. */ export class DisposableList { @@ -53,11 +54,12 @@ export const symbols = { caller: Symbol.for('cordis.caller'), receiver: Symbol.for('cordis.receiver'), original: Symbol.for('cordis.original'), - metadata: Symbol.for('cordis.metadata'), + decorator: Symbol.for('cordis.decorator'), initHooks: Symbol.for('cordis.initHooks'), checkProto: Symbol.for('cordis.checkProto'), // context symbols + root: Symbol.for('cordis.root') as typeof Context.root, effect: Symbol.for('cordis.effect') as typeof Context.effect, filter: Symbol.for('cordis.filter') as typeof Context.filter, isolate: Symbol.for('cordis.isolate') as typeof Context.isolate, @@ -66,11 +68,12 @@ export const symbols = { // service symbols init: Symbol.for('cordis.init') as typeof Service.init, check: Symbol.for('cordis.check') as typeof Service.check, - config: Symbol.for('cordis.config') as typeof Service.config, invoke: Symbol.for('cordis.invoke') as typeof Service.invoke, + metadata: Symbol.for('cordis.metadata') as typeof Service.metadata, extend: Symbol.for('cordis.extend') as typeof Service.extend, tracker: Symbol.for('cordis.tracker') as typeof Service.tracker, - resolveConfig: Symbol.for('cordis.resolveConfig') as typeof Service.resolveConfig, + mergeIntercept: Symbol.for('cordis.mergeIntercept') as typeof Service.mergeIntercept, + resolveIntercept: Symbol.for('cordis.resolveIntercept') as typeof Service.resolveIntercept, } const GeneratorFunction = function* () {}.constructor diff --git a/vendor/include/src/index.ts b/vendor/include/src/index.ts index 5dd86d50ec..8d48f8d2e7 100644 --- a/vendor/include/src/index.ts +++ b/vendor/include/src/index.ts @@ -133,7 +133,7 @@ export class Include extends EntryTree { } private warn = (format: string, ...args: any[]) => { - this.ctx.root.logger?.('loader').warn(format, ...args) + this.ctx[Context.root].logger?.('loader').warn(format, ...args) } async* [Service.init]() { diff --git a/vendor/loader/src/index.ts b/vendor/loader/src/index.ts index ac57527455..2a9e1bb9a3 100644 --- a/vendor/loader/src/index.ts +++ b/vendor/loader/src/index.ts @@ -75,7 +75,7 @@ export namespace Loader { * Subclasses provide persistence by implementing `commit(change)` on `EntryTree`. */ export class Loader extends EntryTree { - declare [Service.config]: Loader.Intercept + declare [Service.metadata]: Loader.Intercept public envData = process.env.CORDIS_SHARED ? JSON.parse(process.env.CORDIS_SHARED) @@ -181,14 +181,14 @@ export class Loader extends EntryTree { } [Service.check]() { - const config: Loader.Intercept = Service.prototype[Service.resolveConfig].call(this) + const config: Loader.Intercept = Service.prototype[Service.resolveIntercept].call(this) if (config.await && this.getTasks().length) return false return true } showLog(entry: Entry, type: string) { if (entry.options.group || !entry.parent.tree.enableLogs) return - this.ctx.root.logger?.('loader').info('%s plugin %C', type, entry.options.name) + this.ctx[Context.root].logger?.('loader').info('%s plugin %C', type, entry.options.name) } /** Return the loader entry id that owns `fiber`, if any. */ From 798d3586bbf02907f02232baf0a3727773df549e Mon Sep 17 00:00:00 2001 From: Shigma Date: Thu, 5 Nov 2026 15:01:48 +0800 Subject: [PATCH 020/404] test(cordis): cover rc.12 validation paths and fix serialized root access --- .../tests/default-product-isolation.e2e.ts | 7 +-- docs/rescope.i18n.yaml | 4 +- docs/rescope.md | 2 +- docs/rescope.zh.md | 2 +- .../guide.i18n.yaml | 8 ++-- .../guide.md | 10 +++-- .../guide.zh.md | 10 +++-- .../inspector/tests/client-browser.e2e.ts | 5 ++- scripts/cordis-core-rc12.spec.ts | 43 +++++++++++++++++-- 9 files changed, 66 insertions(+), 25 deletions(-) diff --git a/apps/web/tests/default-product-isolation.e2e.ts b/apps/web/tests/default-product-isolation.e2e.ts index bc2408e853..7f55e97e81 100644 --- a/apps/web/tests/default-product-isolation.e2e.ts +++ b/apps/web/tests/default-product-isolation.e2e.ts @@ -1,7 +1,7 @@ /** Chromium acceptance of the shipped Web profile's actual Client plugin and module registries. */ -import { Context, FiberState } from '@deepseek-ai/cordis' -import type { Plugin, RegistryService } from '@deepseek-ai/cordis' +import { FiberState } from '@deepseek-ai/cordis' +import type { Context, Plugin, RegistryService } from '@deepseek-ai/cordis' import type { ClientModuleLoader, ClientModuleLoaderTarget } from '@deepseek-ai/dsh-client-modules/client' import { chromium } from 'playwright' import { hasExperimentalPackageReference } from '../../../scripts/experimental-package-policy.ts' @@ -73,7 +73,8 @@ it('activates the actual default Client registry without experimental packages', // Capture the first real root and immediately restore the registry method. prototype.plugin = function (...args: Parameters) { prototype.plugin = plugin - observation.ctx = this.ctx[Context.root] + // This init script runs in the page, where the test's `Context` import is unavailable. + observation.ctx = this.ctx[Symbol.for('cordis.root') as typeof Context.root] return plugin.apply(this, args) } const modules = create(options) diff --git a/docs/rescope.i18n.yaml b/docs/rescope.i18n.yaml index 3eb63034c4..4bff27f2c4 100644 --- a/docs/rescope.i18n.yaml +++ b/docs/rescope.i18n.yaml @@ -6,8 +6,8 @@ en: c8aa4d3384ea1306 zh: 5aa030587d5b634d /vendored-package-rescope/name-mapping: - en: 50a68b9b3724eff8 - zh: 9facad930deeb014 + en: 8d86dcb4f884fb2e + zh: 4886ccf670df1b01 /vendored-package-rescope/what-the-rename-does-not-touch: en: 9bb7d09f8cccf695 zh: 2a8f3f60ae5116f3 diff --git a/docs/rescope.md b/docs/rescope.md index c3ec1d0682..c9d4ceb00a 100644 --- a/docs/rescope.md +++ b/docs/rescope.md @@ -8,7 +8,7 @@ The Cordis framework and its foundation libraries are vendored under [`vendor/`] | Directory | Upstream name | Published name | Upstream version | Role | |---|---|---|---|---| -| `vendor/cordis/` | `cordis` | `@deepseek-ai/cordis` | 4.0.0-rc.11 | Framework core: `Context`, `Service`, `Fiber`, events | +| `vendor/cordis/` | `cordis` | `@deepseek-ai/cordis` | 4.0.0-rc.12 | Framework core: `Context`, `Service`, `Fiber`, events | | `vendor/cosmokit/` | `cosmokit` | `@deepseek-ai/cosmokit` | 1.8.1 | Shared utilities the framework and Schemastery build on | | `vendor/schemastery/` | `schemastery` | `@deepseek-ai/schemastery` | 3.18.0 | Config schemas (`Schema`) behind every plugin's `Config` | | `vendor/loader/` | `@cordisjs/plugin-loader` | `@deepseek-ai/cordis-plugin-loader` | 1.0.0-rc.8 | `cordis.yml` loading, plugin resolution, repository cache | diff --git a/docs/rescope.zh.md b/docs/rescope.zh.md index a02d152204..220e6feebc 100644 --- a/docs/rescope.zh.md +++ b/docs/rescope.zh.md @@ -8,7 +8,7 @@ Cordis 框架及其基础库以源码形式 vendored 在 [`vendor/`](../vendor/R | 目录 | 上游名 | 发布名 | 上游版本 | 角色 | |---|---|---|---|---| -| `vendor/cordis/` | `cordis` | `@deepseek-ai/cordis` | 4.0.0-rc.11 | 框架核心:`Context`、`Service`、`Fiber`、事件 | +| `vendor/cordis/` | `cordis` | `@deepseek-ai/cordis` | 4.0.0-rc.12 | 框架核心:`Context`、`Service`、`Fiber`、事件 | | `vendor/cosmokit/` | `cosmokit` | `@deepseek-ai/cosmokit` | 1.8.1 | 框架与 Schemastery 共用的基础工具 | | `vendor/schemastery/` | `schemastery` | `@deepseek-ai/schemastery` | 3.18.0 | 配置 schema(`Schema`),每个插件的 `Config` 都基于它 | | `vendor/loader/` | `@cordisjs/plugin-loader` | `@deepseek-ai/cordis-plugin-loader` | 1.0.0-rc.8 | `cordis.yml` 装载、插件解析、repository 缓存 | diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.i18n.yaml index f43d1ca56e..f52ca1fc79 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.i18n.yaml @@ -9,8 +9,8 @@ en: 546ad75e75ee931f zh: 16cd20c00e92e6f5 /ctx-context-root-replaces-ctx-root-and-service-intercept-metadata-is-renamed/change: - en: 73b1b7e0bdffb92b - zh: 108e4d9d0d333c36 + en: 84337d9923efc3c6 + zh: e294b792081c7989 /ctx-context-root-replaces-ctx-root-and-service-intercept-metadata-is-renamed/migration: - en: 6080606517656f7e - zh: 1e045b715c3c4946 + en: adec35b8052efcd3 + zh: 56c53d6089761976 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.md index 13d7749096..ce6af127ae 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.md @@ -14,6 +14,7 @@ English | [中文](guide.zh.md) - `ctx.root` no longer exists. The root context is `ctx[Context.root]`; `Context.root` is a symbol exported on the `Context` class. Inside a plugin, reading `ctx.root` throws `cannot get property "root" without inject`. - `Service.config` becomes `Service.metadata`. A service declares its intercept type with `declare [Service.metadata]: T`. - `[Service.resolveConfig](base?, head?)` becomes `[Service.resolveIntercept]()`, which takes no arguments. +- The global symbol `Symbol.for('cordis.metadata')` now keys `Service.metadata`. The method metadata that decorators such as `@Inject()` store moved to `symbols.decorator` (`Symbol.for('cordis.decorator')`). - A service's `Config.merge` hook is no longer called. Override `[Service.mergeIntercept](...values)` instead; it receives the values in increasing precedence. - Metadata a plugin declares in object-form `inject` now has the lowest precedence. Intercepts added with `ctx.intercept()` override it; previously the injected value overrode them. - A context created with `ctx.isolate(name)` no longer falls back to the enclosing plugin's injected `name`. Plugins started under it, and reads after its own provision is withdrawn, throw `cannot get property "" without inject`. @@ -23,7 +24,8 @@ English | [中文](guide.zh.md) 1. Replace every `ctx.root` with `ctx[Context.root]`, importing `Context` as a value from `@deepseek-ai/cordis`. Plain JavaScript without the import can read `ctx[Symbol.for('cordis.root')]`. 2. In service classes, rename `declare [Service.config]` to `declare [Service.metadata]` and calls of `[Service.resolveConfig]()` to `[Service.resolveIntercept]()`. Replace `base` and `head` arguments by declaring the base value in `inject` and adding the override with `ctx.intercept()`. -3. Move a `Config.merge` implementation to a `[Service.mergeIntercept](...values)` method on the service class. -4. Where a plugin relied on its `inject` metadata overriding an ancestor `ctx.intercept()`, set the value with `ctx.intercept()` at the plugin's context instead. -5. Where code under `ctx.isolate(name)` needs the enclosing plugin's service, provide that service inside the isolated context or start the code from a context that is not isolated. -6. Run your TypeScript build: references to `ctx.root`, `Service.config` and `Service.resolveConfig` fail to compile. Start the plugin and confirm that services resolve and logs keep their names. +3. Where code reads or writes decorator method metadata through `symbols.metadata` or `Symbol.for('cordis.metadata')`, use `symbols.decorator` instead. +4. Move a `Config.merge` implementation to a `[Service.mergeIntercept](...values)` method on the service class. +5. Where a plugin relied on its `inject` metadata overriding an ancestor `ctx.intercept()`, set the value with `ctx.intercept()` at the plugin's context instead. +6. Where code under `ctx.isolate(name)` needs the enclosing plugin's service, provide that service inside the isolated context or start the code from a context that is not isolated. +7. Run your TypeScript build: references to `ctx.root`, `Service.config` and `Service.resolveConfig` fail to compile. Start the plugin and confirm that services resolve and logs keep their names. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.zh.md index 981929b671..de78a1c51a 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.zh.md @@ -14,6 +14,7 @@ description: "Cordis 4.0.0-rc.12 用 ctx[Context.root] 取代 ctx.root,并重 - `ctx.root` 不再存在。根上下文改为 `ctx[Context.root]`;`Context.root` 是 `Context` 类上导出的 symbol。在插件内读取 `ctx.root` 会抛出 `cannot get property "root" without inject`。 - `Service.config` 改为 `Service.metadata`。服务用 `declare [Service.metadata]: T` 声明其拦截类型。 - `[Service.resolveConfig](base?, head?)` 改为不带参数的 `[Service.resolveIntercept]()`。 +- 全局 symbol `Symbol.for('cordis.metadata')` 现在对应 `Service.metadata`。`@Inject()` 等装饰器存储的方法元数据改用 `symbols.decorator`(`Symbol.for('cordis.decorator')`)。 - 服务的 `Config.merge` 钩子不再被调用。改为重写 `[Service.mergeIntercept](...values)`;它按优先级从低到高接收各个值。 - 插件在对象形式的 `inject` 中声明的元数据现在优先级最低,用 `ctx.intercept()` 添加的拦截会覆盖它;此前是注入的值覆盖拦截。 - 用 `ctx.isolate(name)` 创建的上下文不再回退到外层插件注入的 `name`。在其下启动的插件,以及在其自身提供撤回后的读取,都会抛出 `cannot get property "" without inject`。 @@ -23,7 +24,8 @@ description: "Cordis 4.0.0-rc.12 用 ctx[Context.root] 取代 ctx.root,并重 1. 将所有 `ctx.root` 替换为 `ctx[Context.root]`,并从 `@deepseek-ai/cordis` 以值的形式导入 `Context`。无法导入的纯 JavaScript 可以读取 `ctx[Symbol.for('cordis.root')]`。 2. 在服务类中,将 `declare [Service.config]` 改为 `declare [Service.metadata]`,将对 `[Service.resolveConfig]()` 的调用改为 `[Service.resolveIntercept]()`。原来的 `base` 参数改为在 `inject` 中声明,`head` 参数改为用 `ctx.intercept()` 添加。 -3. 将 `Config.merge` 的实现移到服务类的 `[Service.mergeIntercept](...values)` 方法中。 -4. 如果插件依赖其 `inject` 元数据覆盖祖先的 `ctx.intercept()`,改为在该插件的上下文上用 `ctx.intercept()` 设置该值。 -5. 如果 `ctx.isolate(name)` 之下的代码需要外层插件的服务,在隔离的上下文中提供该服务,或从未隔离的上下文启动这段代码。 -6. 运行 TypeScript 构建:引用 `ctx.root`、`Service.config` 和 `Service.resolveConfig` 的代码会编译失败。启动插件,确认服务可以解析,日志名称保持不变。 +3. 如果代码通过 `symbols.metadata` 或 `Symbol.for('cordis.metadata')` 读写装饰器的方法元数据,改用 `symbols.decorator`。 +4. 将 `Config.merge` 的实现移到服务类的 `[Service.mergeIntercept](...values)` 方法中。 +5. 如果插件依赖其 `inject` 元数据覆盖祖先的 `ctx.intercept()`,改为在该插件的上下文上用 `ctx.intercept()` 设置该值。 +6. 如果 `ctx.isolate(name)` 之下的代码需要外层插件的服务,在隔离的上下文中提供该服务,或从未隔离的上下文启动这段代码。 +7. 运行 TypeScript 构建:引用 `ctx.root`、`Service.config` 和 `Service.resolveConfig` 的代码会编译失败。启动插件,确认服务可以解析,日志名称保持不变。 diff --git a/packages/experimental/inspector/tests/client-browser.e2e.ts b/packages/experimental/inspector/tests/client-browser.e2e.ts index b7350afba8..f2ef373256 100644 --- a/packages/experimental/inspector/tests/client-browser.e2e.ts +++ b/packages/experimental/inspector/tests/client-browser.e2e.ts @@ -319,8 +319,9 @@ const root = { inject() { return { dispose() {} }; }, provide(name, value) { this[name] = value; return () => { delete this[name]; }; }, }; -root.root = root; -const cordis = { Context: { is(value) { return value?.__inspectorContext === true; } } }; +const rootKey = Symbol.for('cordis.root'); +root[rootKey] = root; +const cordis = { Context: { root: rootKey, is(value) { return value?.__inspectorContext === true; } } }; const plugin = registration.factory(specifier => { if (specifier === '@deepseek-ai/cordis') return cordis; throw new Error('Unexpected Client bundle dependency ' + specifier); diff --git a/scripts/cordis-core-rc12.spec.ts b/scripts/cordis-core-rc12.spec.ts index b706e8b6e3..ef6a8e9564 100644 --- a/scripts/cordis-core-rc12.spec.ts +++ b/scripts/cordis-core-rc12.spec.ts @@ -1,6 +1,6 @@ /** Cordis rc.12 root access, intercept metadata, isolation, disposal and event errors. */ -import { Context, FiberState, Service } from '@deepseek-ai/cordis' -import { describe, expect, it, onTestFinished, vi } from 'vitest' +import { Context, FiberState, Service, ValidationError } from '@deepseek-ai/cordis' +import { describe, expect, it, onTestFinished } from 'vitest' interface Metadata { a?: number @@ -87,6 +87,24 @@ describe('Cordis rc.12 core', () => { expect(results).toEqual(['outer', 'cannot get property "rc12View" without inject']) }) + it('isolates a context pinned to its parent realm label from the injected view', async () => { + const ctx = root() + ctx.provide('rc12View', 'outer') + let message = '' + await ctx.inject(['rc12View'], async (owner) => { + const pinned = owner.isolate('rc12View', owner[Context.isolate].rc12View) + expect(() => pinned.rc12View).toThrow('cannot get property "rc12View" without inject') + await pinned.plugin((child) => { + try { + void child.rc12View + } catch (error) { + message = error instanceof Error ? error.message : String(error) + } + }) + }) + expect(message).toBe('cannot get property "rc12View" without inject') + }) + it('settles pending and failed fibers to DISPOSED', async () => { const ctx = root() const pending = ctx.inject(['rc12NeverProvided'], () => {}) @@ -94,10 +112,9 @@ describe('Cordis rc.12 core', () => { await pending.dispose() expect(pending.state).toBe(FiberState.DISPOSED) - const error = vi.spyOn(ctx.logger('fiber'), 'error').mockImplementation(() => {}) - onTestFinished(() => { error.mockRestore() }) const failed = ctx.plugin(() => { throw new Error('rc12 boom') }) await expect(failed.await()).rejects.toThrow('rc12 boom') + expect(ctx.logger.buffer.some(message => message.type === 'error' && message.args[0] instanceof Error && message.args[0].message === 'rc12 boom')).toBe(true) expect(failed.state).toBe(FiberState.FAILED) await failed.dispose() expect(failed.state).toBe(FiberState.DISPOSED) @@ -111,4 +128,22 @@ describe('Cordis rc.12 core', () => { await expect(ctx.parallel('rc12-parallel' as never)).rejects.toThrow('one or more listeners of event "rc12-parallel" failed') await expect(ctx.parallel(symbol as never)).rejects.toThrow('one or more listeners of event Symbol(rc12-symbol) failed') }) + + it('formats config validation paths with keyed segments', () => { + const error = new ValidationError([{ message: 'bad', path: [{ key: 0 }, 'name'] }]) + expect(ValidationError.is(error)).toBe(true) + expect(ValidationError.is(new TypeError('bad'))).toBe(false) + expect(error.issues).toHaveLength(1) + expect(error.message).toBe('invalid config:\n - bad (at 0.name)') + expect(ValidationError.normalizePath([{ key: 'a' }, 1])).toEqual(['a', 1]) + expect(ValidationError.formatPath(undefined)).toBe('') + expect(new ValidationError([{ message: 'bad', path: [] }]).message).toBe('invalid config:\n - bad') + }) + + it('logs an AggregateError without members as itself', () => { + const ctx = root() + const aggregate = new AggregateError([], 'empty') + ctx.logger.error(aggregate) + expect(ctx.logger.buffer.at(-1)?.args[0]).toBe(aggregate) + }) }) From 1b45ca1a9edacc7b54f24ad2476efa221af3d2c0 Mon Sep 17 00:00:00 2001 From: Shigma Date: Thu, 5 Nov 2026 18:09:49 +0800 Subject: [PATCH 021/404] docs(cordis): document isolate fallback and root symbol access --- docs/cordis-api/context.i18n.yaml | 20 +++++++++--------- docs/cordis-api/context.md | 21 +++++++++++-------- docs/cordis-api/context.zh.md | 21 +++++++++++-------- .../tests/schemastery-json-schema.spec.ts | 2 +- .../generator/tests/cordis-catalog.spec.ts | 2 +- scripts/cordis-core-lifecycle.spec.ts | 4 ++-- vendor/README.md | 2 +- vendor/cordis/src/context.ts | 11 ++++++---- 8 files changed, 46 insertions(+), 37 deletions(-) diff --git a/docs/cordis-api/context.i18n.yaml b/docs/cordis-api/context.i18n.yaml index c0fa96635b..6ac1c40a6d 100644 --- a/docs/cordis-api/context.i18n.yaml +++ b/docs/cordis-api/context.i18n.yaml @@ -12,11 +12,11 @@ en: 18c7f34127f5c5fc zh: fa37a391e9c49f24 /context/ctx-isolate-name-label: - en: e086cbc07d463960 - zh: 7912984e036dbae9 + en: 4b61ce02474b983b + zh: 5ab2948ddcff2687 /context/ctx-intercept-name-config: - en: e4a9d3a55ed550fc - zh: 85ebe8f0d30770e3 + en: 7efc60c71ddc4a6e + zh: 58dd647c41c10897 /context/ctx-baseurl: en: 29c28e7558cea0ad zh: 9b591e449c1bfd72 @@ -36,8 +36,8 @@ en: ceb197529207a8ed zh: 7d444c03f8be0f0d /context/static-members/context-root: - en: ad7203bb4b3533fe - zh: 02b867b883050548 + en: 7616dd841e4f04cb + zh: 2f1a3bdb9ed1f6f7 /context/static-members/context-effect: en: 6c3b77ace7d4fda3 zh: 470c685819275d5f @@ -45,11 +45,11 @@ en: 1c97248eeabea2d0 zh: 08eadac6a0871429 /context/static-members/context-isolate: - en: 471d09c9440bf738 - zh: eecc52f4e5984dbf + en: 6c490ac1293b0315 + zh: 51d371b38de7773a /context/static-members/context-intercept: - en: 57e806faa3abfff6 - zh: 3d32af39e2019758 + en: d3f44b89b641a11b + zh: b88177e0a59ef9a5 /context/static-members/context-is-value: en: 0ef94fa412edfe17 zh: 30b64cd2fbb2d12e diff --git a/docs/cordis-api/context.md b/docs/cordis-api/context.md index f4ab7b76c4..514e2afc0f 100644 --- a/docs/cordis-api/context.md +++ b/docs/cordis-api/context.md @@ -46,6 +46,9 @@ The child prototypally inherits every property of this context; own properties o * resolve against the new label instead of the parent's, so a different * implementation can be provided without affecting the parent scope. * Passing the same `label` to two `isolate()` calls joins their scopes. + * The returned context and plugins started below it never fall back to the + * enclosing plugin's injected `name`, even when `label` equals the parent's + * label; until a provider in the new scope supplies `name`, reading it throws. * * @param name — the service name to isolate. * @param label — scope label to join; defaults to a fresh unique symbol. @@ -56,14 +59,14 @@ isolate(name: string, label?: symbol) Create a child context with an independent service scope for `name`. -Below the returned context, reads and writes of the service `name` resolve against the new label instead of the parent's, so a different implementation can be provided without affecting the parent scope. Passing the same `label` to two `isolate()` calls joins their scopes. +Below the returned context, reads and writes of the service `name` resolve against the new label instead of the parent's, so a different implementation can be provided without affecting the parent scope. Passing the same `label` to two `isolate()` calls joins their scopes. The returned context and plugins started below it never fall back to the enclosing plugin's injected `name`, even when `label` equals the parent's label; until a provider in the new scope supplies `name`, reading it throws. - `name` — the service name to isolate. - `label` — scope label to join; defaults to a fresh unique symbol. **Returns** a child context whose `name` service resolves in the new scope. -[Source](../../vendor/cordis/src/context.ts#L123) +[Source](../../vendor/cordis/src/context.ts#L126) ### ctx.intercept(name, config) @@ -94,7 +97,7 @@ Plugins loaded under the returned context see `config` merged into the service's **Returns** a child context carrying the additional intercept entry. -[Source](../../vendor/cordis/src/context.ts#L142) +[Source](../../vendor/cordis/src/context.ts#L145) ### ctx.baseUrl @@ -156,11 +159,11 @@ The plugin registry. Its methods are mixed onto `ctx` (`ctx.plugin`, `ctx.inject ### Context.root ```ts cordis-catalog -/** Symbol key of the root context (see the `Context[symbols.root]` property). */ +/** Symbol key of the root context: `ctx[Context.root]` is the application's root context, shared by every child context. */ static readonly root: unique symbol ``` -Symbol key of the root context (see the `Context[symbols.root]` property). +Symbol key of the root context: `ctx[Context.root]` is the application's root context, shared by every child context. [Source](../../vendor/cordis/src/context.ts#L44) @@ -189,22 +192,22 @@ Symbol key for a context's listener filter, consulted on every event dispatch. ### Context.isolate ```ts cordis-catalog -/** Symbol key of the isolation map (see the `Context[symbols.isolate]` property). */ +/** Symbol key of the isolation map: `ctx[Context.isolate]` maps each service name to its scope label. */ static readonly isolate: unique symbol ``` -Symbol key of the isolation map (see the `Context[symbols.isolate]` property). +Symbol key of the isolation map: `ctx[Context.isolate]` maps each service name to its scope label. [Source](../../vendor/cordis/src/context.ts#L50) ### Context.intercept ```ts cordis-catalog -/** Symbol key of the intercept map (see the `Context[symbols.intercept]` property). */ +/** Symbol key of the intercept map: `ctx[Context.intercept]` maps each service name to its intercept metadata. */ static readonly intercept: unique symbol ``` -Symbol key of the intercept map (see the `Context[symbols.intercept]` property). +Symbol key of the intercept map: `ctx[Context.intercept]` maps each service name to its intercept metadata. [Source](../../vendor/cordis/src/context.ts#L52) diff --git a/docs/cordis-api/context.zh.md b/docs/cordis-api/context.zh.md index c923a56445..b5ff13c4eb 100644 --- a/docs/cordis-api/context.zh.md +++ b/docs/cordis-api/context.zh.md @@ -48,6 +48,9 @@ extend(meta = {}): this * resolve against the new label instead of the parent's, so a different * implementation can be provided without affecting the parent scope. * Passing the same `label` to two `isolate()` calls joins their scopes. + * The returned context and plugins started below it never fall back to the + * enclosing plugin's injected `name`, even when `label` equals the parent's + * label; until a provider in the new scope supplies `name`, reading it throws. * * @param name — the service name to isolate. * @param label — scope label to join; defaults to a fresh unique symbol. @@ -58,14 +61,14 @@ isolate(name: string, label?: symbol) 创建一个子上下文,使 `name` 拥有独立的服务作用域。 -在返回的上下文之下,对服务 `name` 的读写会根据新标签解析,而不再根据父上下文的标签解析,因此可以提供不同的实现而不影响父作用域。将同一个 `label` 传给两次 `isolate()` 调用,可使二者加入同一作用域。 +在返回的上下文之下,对服务 `name` 的读写会根据新标签解析,而不再根据父上下文的标签解析,因此可以提供不同的实现而不影响父作用域。将同一个 `label` 传给两次 `isolate()` 调用,可使二者加入同一作用域。返回的上下文及在其下启动的插件都不会回退到外层插件注入的 `name`,即使 `label` 与父上下文的标签相同也是如此;在新作用域中有提供者提供 `name` 之前,读取它会抛出错误。 - `name`:要隔离的服务名称。 - `label`:要加入的作用域标签;默认为一个新建的唯一 symbol。 **返回**一个子上下文,其 `name` 服务在新作用域中解析。 -[源码](../../vendor/cordis/src/context.ts#L123) +[源码](../../vendor/cordis/src/context.ts#L126) ### ctx.intercept(name, config) @@ -96,7 +99,7 @@ intercept(name: string, config: any): this **返回**一个携带额外拦截条目的子上下文。 -[源码](../../vendor/cordis/src/context.ts#L142) +[源码](../../vendor/cordis/src/context.ts#L145) ### ctx.baseUrl @@ -158,11 +161,11 @@ registry: RegistryService ### Context.root ```ts cordis-catalog -/** Symbol key of the root context (see the `Context[symbols.root]` property). */ +/** Symbol key of the root context: `ctx[Context.root]` is the application's root context, shared by every child context. */ static readonly root: unique symbol ``` -根上下文的 symbol 键(见 `Context[symbols.root]` 属性)。 +根上下文的 symbol 键:`ctx[Context.root]` 是应用的根上下文,所有子上下文共享它。 [源码](../../vendor/cordis/src/context.ts#L44) @@ -191,22 +194,22 @@ static readonly filter: unique symbol ### Context.isolate ```ts cordis-catalog -/** Symbol key of the isolation map (see the `Context[symbols.isolate]` property). */ +/** Symbol key of the isolation map: `ctx[Context.isolate]` maps each service name to its scope label. */ static readonly isolate: unique symbol ``` -隔离映射的 symbol 键(见 `Context[symbols.isolate]` 属性)。 +隔离映射的 symbol 键:`ctx[Context.isolate]` 将每个服务名称映射到其作用域标签。 [源码](../../vendor/cordis/src/context.ts#L50) ### Context.intercept ```ts cordis-catalog -/** Symbol key of the intercept map (see the `Context[symbols.intercept]` property). */ +/** Symbol key of the intercept map: `ctx[Context.intercept]` maps each service name to its intercept metadata. */ static readonly intercept: unique symbol ``` -拦截映射的 symbol 键(见 `Context[symbols.intercept]` 属性)。 +拦截映射的 symbol 键:`ctx[Context.intercept]` 将每个服务名称映射到其拦截元数据。 [源码](../../vendor/cordis/src/context.ts#L52) diff --git a/packages/boot/app-boot/tests/schemastery-json-schema.spec.ts b/packages/boot/app-boot/tests/schemastery-json-schema.spec.ts index acbe7c5432..84d79c954d 100644 --- a/packages/boot/app-boot/tests/schemastery-json-schema.spec.ts +++ b/packages/boot/app-boot/tests/schemastery-json-schema.spec.ts @@ -343,7 +343,7 @@ describe('Schemastery input projection', () => { expect(accepts(result, { children: [{ children: [] }] })).toBe(true) expect(result.limitations.join(' ')).toContain('recursive default') expect(result.definitions.testRecursive0).not.toHaveProperty('anyOf') - expect(accepts(result, { __jsExpr: 'ctx.root' })).toBe(true) + expect(accepts(result, { __jsExpr: 'ctx[Symbol.for("cordis.root")]' })).toBe(true) expect(accepts(result, { children: [{ __jsExpr: 'ctx.child' }] })).toBe(true) expect(accepts(result, { children: [3] })).toBe(false) expect(JSON.stringify(result)).not.toContain('"uid"') diff --git a/packages/typert/generator/tests/cordis-catalog.spec.ts b/packages/typert/generator/tests/cordis-catalog.spec.ts index ab91b9d157..8e1fcfb1f7 100644 --- a/packages/typert/generator/tests/cordis-catalog.spec.ts +++ b/packages/typert/generator/tests/cordis-catalog.spec.ts @@ -34,7 +34,7 @@ const SOURCE_LINK_POLICY: CordisCatalogPolicy = { foundationTypeNames: new Set(), typeLinkExemptions: {}, inheritedEvents: [{ name: 'ready', summary: 'Ready.', source: 'vendor/cordis/src/events.ts:9' }], - inheritedServices: [{ name: 'ctx.root', summary: 'Root.', source: 'vendor/cordis/src/context.ts:12' }], + inheritedServices: [{ name: 'ctx.events', summary: 'Events.', source: 'vendor/cordis/src/context.ts:12' }], } describe('Typert-backed Cordis catalog', () => { diff --git a/scripts/cordis-core-lifecycle.spec.ts b/scripts/cordis-core-lifecycle.spec.ts index becd02fa37..21c698d1a3 100644 --- a/scripts/cordis-core-lifecycle.spec.ts +++ b/scripts/cordis-core-lifecycle.spec.ts @@ -1,4 +1,4 @@ -/** Cordis rc.11 updates retain dependency ownership and publish only current configuration. */ +/** Cordis lifecycle since rc.11 (vendored Core): updates retain dependency ownership and publish only current configuration. */ import type { Awaitable } from '@deepseek-ai/cosmokit' import { Context, FiberState } from '@deepseek-ai/cordis' import { describe, expect, it, onTestFinished, vi } from 'vitest' @@ -110,7 +110,7 @@ describe('Cordis rc.11 lifecycle', () => { await isolated.plugin((child) => { expect(child.rc11View).toBe('inner') }) await withdraw() expect(owner.rc11View).toBe('outer') - // The isolated context does not fall back to the injected view once its own provision is withdrawn. + // Since rc.12, the isolated context does not fall back to the injected view once its own provision is withdrawn. expect(() => isolated.rc11View).toThrow('without inject') }) await ctx.plugin((owner) => { diff --git a/vendor/README.md b/vendor/README.md index a13f62d275..c39c3710a8 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 - **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'`. Core's upstream source already uses explicit `.ts` specifiers. 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. `[Context.root]`), module re-exports, shared utility helpers, `EventsService`, `Fiber`, `ValidationError` and its path helpers, `RegistryService`, `ReflectService`, `Service` and its intercept-metadata members, `LoggerService` and their `declare module './context.ts'` overloads. The upstream line comment on `reflect.ts`'s exported `locate()` is rewritten as JSDoc. 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 · 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, the `isolate()` rule that isolated scopes never fall back to an injected view, and the `Context` interface properties incl. `[Context.root]`), module re-exports, shared utility helpers, `EventsService`, `Fiber`, `ValidationError` and its path helpers, `RegistryService`, `ReflectService`, `Service` and its intercept-metadata members, `LoggerService` and their `declare module './context.ts'` overloads. The upstream line comment on `reflect.ts`'s exported `locate()` is rewritten as JSDoc. 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. - **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`. diff --git a/vendor/cordis/src/context.ts b/vendor/cordis/src/context.ts index 951a0ddae4..5cbb27d6c6 100644 --- a/vendor/cordis/src/context.ts +++ b/vendor/cordis/src/context.ts @@ -18,7 +18,7 @@ export interface Context { [symbols.root]: this /** Isolation map: service name → scope label. Lookups for a name resolve within its label. */ [symbols.isolate]: Dict - /** Intercept map: service name → config merged into that service's per-plugin config. */ + /** Intercept map: service name → intercept metadata merged into that service's resolved metadata. */ [symbols.intercept]: Dict /** Base URL used to resolve relative plugin/module specifiers, if the runtime sets one. */ baseUrl?: string | undefined @@ -40,15 +40,15 @@ export interface Context { * contexts without mutating their parent. */ export class Context { - /** Symbol key of the root context (see the `Context[symbols.root]` property). */ + /** Symbol key of the root context: `ctx[Context.root]` is the application's root context, shared by every child context. */ static readonly root: unique symbol = symbols.root /** Symbol key under which a disposer exposes its {@link EffectMeta} diagnostics tree. */ static readonly effect: unique symbol = symbols.effect /** Symbol key for a context's listener filter, consulted on every event dispatch. */ static readonly filter: unique symbol = symbols.filter - /** Symbol key of the isolation map (see the `Context[symbols.isolate]` property). */ + /** Symbol key of the isolation map: `ctx[Context.isolate]` maps each service name to its scope label. */ static readonly isolate: unique symbol = symbols.isolate - /** Symbol key of the intercept map (see the `Context[symbols.intercept]` property). */ + /** Symbol key of the intercept map: `ctx[Context.intercept]` maps each service name to its intercept metadata. */ static readonly intercept: unique symbol = symbols.intercept /** @@ -115,6 +115,9 @@ export class Context { * resolve against the new label instead of the parent's, so a different * implementation can be provided without affecting the parent scope. * Passing the same `label` to two `isolate()` calls joins their scopes. + * The returned context and plugins started below it never fall back to the + * enclosing plugin's injected `name`, even when `label` equals the parent's + * label; until a provider in the new scope supplies `name`, reading it throws. * * @param name — the service name to isolate. * @param label — scope label to join; defaults to a fresh unique symbol. From d9421f3e0315239a61c8ad2c728be7e1ebb10a01 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Thu, 5 Nov 2026 21:12:27 +0800 Subject: [PATCH 022/404] test(web): expect the turn rail at the scrollport start edge The Session panel moves the turn rail from the end edge of the Conversation scrollport to its start edge, leaving the end gutter to the panel. The floating-controls geometry check now measures the rail's 12px inset from the scrollport's start edge instead of its end edge. --- apps/web/tests/chat-scroll-contract.e2e.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/tests/chat-scroll-contract.e2e.ts b/apps/web/tests/chat-scroll-contract.e2e.ts index fd5f778c1e..20365f6478 100644 --- a/apps/web/tests/chat-scroll-contract.e2e.ts +++ b/apps/web/tests/chat-scroll-contract.e2e.ts @@ -1237,7 +1237,7 @@ describe('web e2e: long Chat scroll contract', () => { const top = viewport.top + element.clientTop return Math.max( Math.abs((railBox.top + railBox.bottom) / 2 - (top + composerBox.top) / 2), - Math.abs(viewport.left + element.clientLeft + element.clientWidth - railBox.right - 12), + Math.abs(railBox.left - viewport.left - element.clientLeft - 12), Math.abs(composerBox.top - buttonBox.bottom - 16), ) }), { timeout: 10_000 }).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) From e0ad8405df8dea24b85378dd472a52c411f1c593 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Thu, 5 Nov 2026 21:12:29 +0800 Subject: [PATCH 023/404] test(web): refresh goldens for the Session panel toggle The Session panel toggle is the first Session header utility, so every Session header ARIA golden gains its button ("Session panel", or the localized name in the Chinese and Japanese cases) before "More actions". --- .../tests/expected/agent-preset-selection/header.expected.md | 1 + apps/web/tests/expected/clickable-links-gallery/ui.expected.md | 1 + apps/web/tests/expected/cordis-history/ui.expected.md | 1 + .../github-ready-review/conversation-expanded.expected.md | 1 + .../expected/github-ready-review/conversation.expected.md | 1 + .../tests/expected/goal-command-presentation/ui.expected.md | 1 + apps/web/tests/expected/markdown-cjk-strong/ui.expected.md | 1 + apps/web/tests/expected/markdown-images/ui.expected.md | 1 + .../tests/expected/markdown-inline-code-links/ui.expected.md | 1 + apps/web/tests/expected/math-rendering/ui.expected.md | 1 + apps/web/tests/expected/reference-composer/order.expected.md | 1 + .../sidebar-subagent-activity/compact-running.expected.md | 1 + .../tests/expected/skill-user-invoke/ui-expanded.expected.md | 1 + apps/web/tests/expected/skill-user-invoke/ui.expected.md | 1 + apps/web/tests/expected/stats-paged-history/ui.expected.md | 1 + apps/web/tests/expected/steer-all/mid-steer.expected.md | 1 + apps/web/tests/expected/steer-all/settled-expanded.expected.md | 1 + apps/web/tests/expected/steer-all/settled.expected.md | 1 + .../snapshots/streaming-fence-highlight/mid-stream.expected.md | 1 + snapshots/web/auto-review-approval/ui.expected.md | 2 ++ snapshots/web/auto-review-denial/ui.expected.md | 3 +++ snapshots/web/bash-abort-row/ui.expected.md | 1 + snapshots/web/deepseek-messages-chat/ui.expected.md | 1 + snapshots/web/default-workspace/ui.expected.md | 1 + snapshots/web/feedback-command/ack-expanded.expected.md | 1 + snapshots/web/feedback-command/ack.expected.md | 1 + snapshots/web/feedback-release/ack-expanded.expected.md | 1 + snapshots/web/feedback-release/ack.expected.md | 1 + snapshots/web/file-upload-round/ui.expected.md | 1 + snapshots/web/fresh-round-trip/ui-expanded.expected.md | 1 + snapshots/web/fresh-round-trip/ui.expected.md | 1 + snapshots/web/goal-multi-turn-actions/ui-expanded.expected.md | 1 + snapshots/web/goal-multi-turn-actions/ui.expected.md | 1 + snapshots/web/interrupted-turn/ui.expected.md | 1 + snapshots/web/lifecycle-chrome/reloaded-expanded.expected.md | 1 + snapshots/web/lifecycle-chrome/reloaded.expected.md | 1 + snapshots/web/live-interactions/cancel-expanded.expected.md | 1 + snapshots/web/live-interactions/cancel.expected.md | 1 + snapshots/web/live-interactions/continued.expected.md | 1 + snapshots/web/live-interactions/error-auth.expected.md | 1 + snapshots/web/live-interactions/loading.expected.md | 1 + snapshots/web/live-interactions/retry-exhausted.expected.md | 1 + snapshots/web/live-interactions/retry-expanded.expected.md | 1 + snapshots/web/live-interactions/retry.expected.md | 1 + snapshots/web/live-interactions/running-draft.expected.md | 1 + snapshots/web/message-actions/ui.expected.md | 1 + snapshots/web/minimal-compact/ui.expected.md | 1 + snapshots/web/minimal-preset/ui.expected.md | 1 + snapshots/web/minimal-read-image/ui.expected.md | 1 + snapshots/web/open-in-app-ssh/header.expected.md | 1 + snapshots/web/plan-review/approved-expanded.expected.md | 1 + snapshots/web/plan-review/approved.expected.md | 1 + snapshots/web/present/ui.expected.md | 1 + snapshots/web/ptc-round/ui-ja.expected.md | 1 + snapshots/web/ptc-round/ui.expected.md | 1 + snapshots/web/question-composer/answered-expanded.expected.md | 1 + snapshots/web/question-composer/answered.expected.md | 1 + snapshots/web/question-composer/cancelled.expected.md | 1 + snapshots/web/question-composer/late-answered.expected.md | 1 + snapshots/web/question-composer/queued.expected.md | 1 + snapshots/web/queue-actions/collapsed.expected.md | 1 + snapshots/web/queue-actions/editing.expected.md | 1 + snapshots/web/queue-actions/goal-stop.expected.md | 1 + snapshots/web/queue-actions/layout.expected.md | 1 + snapshots/web/queue-actions/preserved-expanded.expected.md | 1 + snapshots/web/queue-actions/preserved.expected.md | 1 + snapshots/web/queue-actions/sending.expected.md | 1 + snapshots/web/queue-actions/ui.expected.md | 1 + snapshots/web/queued-image/delivered.expected.md | 1 + snapshots/web/queued-image/queued.expected.md | 1 + snapshots/web/rich-text-quotes/ui.expected.md | 1 + snapshots/web/seeded-history/command-row.expected.md | 1 + snapshots/web/seeded-history/feedback-row.expected.md | 1 + snapshots/web/seeded-history/ui-expanded.expected.md | 1 + snapshots/web/seeded-history/ui.expected.md | 1 + snapshots/web/skill-tool-row/ui.expected.md | 1 + snapshots/web/steering/mid-steer.expected.md | 1 + snapshots/web/steering/settled-expanded.expected.md | 1 + snapshots/web/steering/settled.expected.md | 1 + snapshots/web/steering/trajectory.expected.md | 1 + snapshots/web/subagent-conversation/nested.expected.md | 1 + snapshots/web/subagent-conversation/ui-expanded.expected.md | 1 + snapshots/web/subagent-conversation/ui.expected.md | 1 + snapshots/web/subagent-interrupt/image-queue.expected.md | 1 + snapshots/web/subagent-interrupt/offline-composer.expected.md | 1 + snapshots/web/turn-tail-actions/completed.expected.md | 1 + snapshots/web/turn-tail-actions/focused.expected.md | 1 + snapshots/web/turn-tail-actions/running.expected.md | 1 + snapshots/web/turn-tail-actions/settled.expected.md | 1 + snapshots/web/turn-tail-actions/usage-expanded.expected.md | 1 + snapshots/web/web-search-round/ui.expected.md | 1 + 91 files changed, 94 insertions(+) diff --git a/apps/web/tests/expected/agent-preset-selection/header.expected.md b/apps/web/tests/expected/agent-preset-selection/header.expected.md index 2b87066124..3b3e5e3f6e 100644 --- a/apps/web/tests/expected/agent-preset-selection/header.expected.md +++ b/apps/web/tests/expected/agent-preset-selection/header.expected.md @@ -1,5 +1,6 @@ - navigation "Session hierarchy": Seeded turn - text: Minimal mode - button "1 subagent" +- button "Session panel" - button "More actions" - button "Open right sidebar" diff --git a/apps/web/tests/expected/clickable-links-gallery/ui.expected.md b/apps/web/tests/expected/clickable-links-gallery/ui.expected.md index 50cd7bc896..aeecf7ad1c 100644 --- a/apps/web/tests/expected/clickable-links-gallery/ui.expected.md +++ b/apps/web/tests/expected/clickable-links-gallery/ui.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Clickable links gallery + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/cordis-history/ui.expected.md b/apps/web/tests/expected/cordis-history/ui.expected.md index 32e5cba5bc..56eb15e136 100644 --- a/apps/web/tests/expected/cordis-history/ui.expected.md +++ b/apps/web/tests/expected/cordis-history/ui.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Use only Cordis tools. First + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/github-ready-review/conversation-expanded.expected.md b/apps/web/tests/expected/github-ready-review/conversation-expanded.expected.md index b0546d4998..c75151fd81 100644 --- a/apps/web/tests/expected/github-ready-review/conversation-expanded.expected.md +++ b/apps/web/tests/expected/github-ready-review/conversation-expanded.expected.md @@ -11,6 +11,7 @@ - banner: - navigation "Session hierarchy": Review deepseek-ai/deepseek-harness#314 - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/github-ready-review/conversation.expected.md b/apps/web/tests/expected/github-ready-review/conversation.expected.md index 9b10e08416..df6aabe092 100644 --- a/apps/web/tests/expected/github-ready-review/conversation.expected.md +++ b/apps/web/tests/expected/github-ready-review/conversation.expected.md @@ -11,6 +11,7 @@ - banner: - navigation "Session hierarchy": Review deepseek-ai/deepseek-harness#314 - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/goal-command-presentation/ui.expected.md b/apps/web/tests/expected/goal-command-presentation/ui.expected.md index ac468809d2..60dcaaa04a 100644 --- a/apps/web/tests/expected/goal-command-presentation/ui.expected.md +++ b/apps/web/tests/expected/goal-command-presentation/ui.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": workspace - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/markdown-cjk-strong/ui.expected.md b/apps/web/tests/expected/markdown-cjk-strong/ui.expected.md index 6eee07ead9..a8f1951ae4 100644 --- a/apps/web/tests/expected/markdown-cjk-strong/ui.expected.md +++ b/apps/web/tests/expected/markdown-cjk-strong/ui.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": CJK strong emphasis + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/markdown-images/ui.expected.md b/apps/web/tests/expected/markdown-images/ui.expected.md index 4923acd2e6..b3fbac6447 100644 --- a/apps/web/tests/expected/markdown-images/ui.expected.md +++ b/apps/web/tests/expected/markdown-images/ui.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Markdown image policy + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/markdown-inline-code-links/ui.expected.md b/apps/web/tests/expected/markdown-inline-code-links/ui.expected.md index d2d68c6021..403c938a2b 100644 --- a/apps/web/tests/expected/markdown-inline-code-links/ui.expected.md +++ b/apps/web/tests/expected/markdown-inline-code-links/ui.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Inline code links + - button "Session panel" - button "More actions" - tablist: - tab "Chat" [selected] diff --git a/apps/web/tests/expected/math-rendering/ui.expected.md b/apps/web/tests/expected/math-rendering/ui.expected.md index 82c51f246e..b31a0cb736 100644 --- a/apps/web/tests/expected/math-rendering/ui.expected.md +++ b/apps/web/tests/expected/math-rendering/ui.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Math rendering + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/reference-composer/order.expected.md b/apps/web/tests/expected/reference-composer/order.expected.md index e13baba024..f2a467af85 100644 --- a/apps/web/tests/expected/reference-composer/order.expected.md +++ b/apps/web/tests/expected/reference-composer/order.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Reference order target + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/sidebar-subagent-activity/compact-running.expected.md b/apps/web/tests/expected/sidebar-subagent-activity/compact-running.expected.md index 7a26f1bae7..6e56147a9a 100644 --- a/apps/web/tests/expected/sidebar-subagent-activity/compact-running.expected.md +++ b/apps/web/tests/expected/sidebar-subagent-activity/compact-running.expected.md @@ -2,6 +2,7 @@ - navigation "Session hierarchy": Delegate a background job. - button "1 subagent" - button "1 background job" + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/skill-user-invoke/ui-expanded.expected.md b/apps/web/tests/expected/skill-user-invoke/ui-expanded.expected.md index 4c06982b08..c7a72552a8 100644 --- a/apps/web/tests/expected/skill-user-invoke/ui-expanded.expected.md +++ b/apps/web/tests/expected/skill-user-invoke/ui-expanded.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": /user-invoke-demo @"meeting notes-this-i - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/skill-user-invoke/ui.expected.md b/apps/web/tests/expected/skill-user-invoke/ui.expected.md index db8db2840a..d13ca7947f 100644 --- a/apps/web/tests/expected/skill-user-invoke/ui.expected.md +++ b/apps/web/tests/expected/skill-user-invoke/ui.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": /user-invoke-demo @"meeting notes-this-i - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/stats-paged-history/ui.expected.md b/apps/web/tests/expected/stats-paged-history/ui.expected.md index 34f3cf897d..b69dca50c7 100644 --- a/apps/web/tests/expected/stats-paged-history/ui.expected.md +++ b/apps/web/tests/expected/stats-paged-history/ui.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": {{workspace}} + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/steer-all/mid-steer.expected.md b/apps/web/tests/expected/steer-all/mid-steer.expected.md index dd9afda70c..b917214246 100644 --- a/apps/web/tests/expected/steer-all/mid-steer.expected.md +++ b/apps/web/tests/expected/steer-all/mid-steer.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Use the ask_user_question tool to - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/steer-all/settled-expanded.expected.md b/apps/web/tests/expected/steer-all/settled-expanded.expected.md index 3977249952..65213117f6 100644 --- a/apps/web/tests/expected/steer-all/settled-expanded.expected.md +++ b/apps/web/tests/expected/steer-all/settled-expanded.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Use the ask_user_question tool to - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/steer-all/settled.expected.md b/apps/web/tests/expected/steer-all/settled.expected.md index 903a4d6021..db22bb3b36 100644 --- a/apps/web/tests/expected/steer-all/settled.expected.md +++ b/apps/web/tests/expected/steer-all/settled.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Use the ask_user_question tool to - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md b/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md index 94a7638c3f..64585d3be8 100644 --- a/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md +++ b/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Stream one TypeScript fence for - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/auto-review-approval/ui.expected.md b/snapshots/web/auto-review-approval/ui.expected.md index ac943a33c9..117b92e6a4 100644 --- a/snapshots/web/auto-review-approval/ui.expected.md +++ b/snapshots/web/auto-review-approval/ui.expected.md @@ -2,6 +2,7 @@ - banner: - navigation "Session hierarchy": {{workspace}} + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: @@ -28,6 +29,7 @@ - banner: - navigation "Session hierarchy": {{workspace}} + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/auto-review-denial/ui.expected.md b/snapshots/web/auto-review-denial/ui.expected.md index f9b78c5d2e..5b166d0a43 100644 --- a/snapshots/web/auto-review-denial/ui.expected.md +++ b/snapshots/web/auto-review-denial/ui.expected.md @@ -2,6 +2,7 @@ - banner: - navigation "Session hierarchy": {{workspace}} + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: @@ -29,6 +30,7 @@ - banner: - navigation "Session hierarchy": {{workspace}} + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: @@ -60,6 +62,7 @@ - banner: - navigation "Session hierarchy": {{workspace}} + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/bash-abort-row/ui.expected.md b/snapshots/web/bash-abort-row/ui.expected.md index ac3d5ef116..743150b624 100644 --- a/snapshots/web/bash-abort-row/ui.expected.md +++ b/snapshots/web/bash-abort-row/ui.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": "Run two shell commands: wait" + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/deepseek-messages-chat/ui.expected.md b/snapshots/web/deepseek-messages-chat/ui.expected.md index 45809754a0..28d071f826 100644 --- a/snapshots/web/deepseek-messages-chat/ui.expected.md +++ b/snapshots/web/deepseek-messages-chat/ui.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "会话层级": 只回复 MESSAGES_WEB_READY,不调用 - text: 标准模式 + - button "会话面板" - button "更多操作" - button "打开右侧边栏" - tablist: diff --git a/snapshots/web/default-workspace/ui.expected.md b/snapshots/web/default-workspace/ui.expected.md index e88f5075a5..5946a56d28 100644 --- a/snapshots/web/default-workspace/ui.expected.md +++ b/snapshots/web/default-workspace/ui.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Use the bash tool to - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/feedback-command/ack-expanded.expected.md b/snapshots/web/feedback-command/ack-expanded.expected.md index eb65a5453b..f829859e41 100644 --- a/snapshots/web/feedback-command/ack-expanded.expected.md +++ b/snapshots/web/feedback-command/ack-expanded.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with the single word - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/feedback-command/ack.expected.md b/snapshots/web/feedback-command/ack.expected.md index 46ff8dc952..3e38912f14 100644 --- a/snapshots/web/feedback-command/ack.expected.md +++ b/snapshots/web/feedback-command/ack.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with the single word - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/feedback-release/ack-expanded.expected.md b/snapshots/web/feedback-release/ack-expanded.expected.md index eb65a5453b..f829859e41 100644 --- a/snapshots/web/feedback-release/ack-expanded.expected.md +++ b/snapshots/web/feedback-release/ack-expanded.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with the single word - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/feedback-release/ack.expected.md b/snapshots/web/feedback-release/ack.expected.md index 46ff8dc952..3e38912f14 100644 --- a/snapshots/web/feedback-release/ack.expected.md +++ b/snapshots/web/feedback-release/ack.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with the single word - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/file-upload-round/ui.expected.md b/snapshots/web/file-upload-round/ui.expected.md index a3e682317c..48464607ba 100644 --- a/snapshots/web/file-upload-round/ui.expected.md +++ b/snapshots/web/file-upload-round/ui.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Read the attached file with - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/fresh-round-trip/ui-expanded.expected.md b/snapshots/web/fresh-round-trip/ui-expanded.expected.md index 919216af28..f9d0ec7b1f 100644 --- a/snapshots/web/fresh-round-trip/ui-expanded.expected.md +++ b/snapshots/web/fresh-round-trip/ui-expanded.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Use the bash tool to - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/fresh-round-trip/ui.expected.md b/snapshots/web/fresh-round-trip/ui.expected.md index e88f5075a5..5946a56d28 100644 --- a/snapshots/web/fresh-round-trip/ui.expected.md +++ b/snapshots/web/fresh-round-trip/ui.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Use the bash tool to - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/goal-multi-turn-actions/ui-expanded.expected.md b/snapshots/web/goal-multi-turn-actions/ui-expanded.expected.md index f3573f01d2..bcd429686e 100644 --- a/snapshots/web/goal-multi-turn-actions/ui-expanded.expected.md +++ b/snapshots/web/goal-multi-turn-actions/ui-expanded.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": workspace - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/goal-multi-turn-actions/ui.expected.md b/snapshots/web/goal-multi-turn-actions/ui.expected.md index 1b47544f84..c35449101b 100644 --- a/snapshots/web/goal-multi-turn-actions/ui.expected.md +++ b/snapshots/web/goal-multi-turn-actions/ui.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": workspace - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/interrupted-turn/ui.expected.md b/snapshots/web/interrupted-turn/ui.expected.md index f3b5c777b2..3d53c7b2a9 100644 --- a/snapshots/web/interrupted-turn/ui.expected.md +++ b/snapshots/web/interrupted-turn/ui.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Use the read tool twice + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/lifecycle-chrome/reloaded-expanded.expected.md b/snapshots/web/lifecycle-chrome/reloaded-expanded.expected.md index c4820a8dc9..b538569ac1 100644 --- a/snapshots/web/lifecycle-chrome/reloaded-expanded.expected.md +++ b/snapshots/web/lifecycle-chrome/reloaded-expanded.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with the single word - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/lifecycle-chrome/reloaded.expected.md b/snapshots/web/lifecycle-chrome/reloaded.expected.md index bf189ee365..e29fb2d595 100644 --- a/snapshots/web/lifecycle-chrome/reloaded.expected.md +++ b/snapshots/web/lifecycle-chrome/reloaded.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with the single word - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/live-interactions/cancel-expanded.expected.md b/snapshots/web/live-interactions/cancel-expanded.expected.md index 2d5c0c5bba..83a2c85d77 100644 --- a/snapshots/web/live-interactions/cancel-expanded.expected.md +++ b/snapshots/web/live-interactions/cancel-expanded.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with a one-sentence description - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/live-interactions/cancel.expected.md b/snapshots/web/live-interactions/cancel.expected.md index ee2791a0a0..e21f0570b0 100644 --- a/snapshots/web/live-interactions/cancel.expected.md +++ b/snapshots/web/live-interactions/cancel.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with a one-sentence description - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/live-interactions/continued.expected.md b/snapshots/web/live-interactions/continued.expected.md index da8fc50a28..3fa4d33867 100644 --- a/snapshots/web/live-interactions/continued.expected.md +++ b/snapshots/web/live-interactions/continued.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with a one-sentence description - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/live-interactions/error-auth.expected.md b/snapshots/web/live-interactions/error-auth.expected.md index e7e5f34c64..f5eaffda23 100644 --- a/snapshots/web/live-interactions/error-auth.expected.md +++ b/snapshots/web/live-interactions/error-auth.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with a one-sentence description - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/live-interactions/loading.expected.md b/snapshots/web/live-interactions/loading.expected.md index 28141fb63e..64591b021f 100644 --- a/snapshots/web/live-interactions/loading.expected.md +++ b/snapshots/web/live-interactions/loading.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with a one-sentence description - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/live-interactions/retry-exhausted.expected.md b/snapshots/web/live-interactions/retry-exhausted.expected.md index 2269e99eb8..b6ebe548b0 100644 --- a/snapshots/web/live-interactions/retry-exhausted.expected.md +++ b/snapshots/web/live-interactions/retry-exhausted.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with a one-sentence description - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/live-interactions/retry-expanded.expected.md b/snapshots/web/live-interactions/retry-expanded.expected.md index ff0b7922ca..8da764297e 100644 --- a/snapshots/web/live-interactions/retry-expanded.expected.md +++ b/snapshots/web/live-interactions/retry-expanded.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with a one-sentence description - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/live-interactions/retry.expected.md b/snapshots/web/live-interactions/retry.expected.md index 00133d103c..5848e82e74 100644 --- a/snapshots/web/live-interactions/retry.expected.md +++ b/snapshots/web/live-interactions/retry.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with a one-sentence description - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/live-interactions/running-draft.expected.md b/snapshots/web/live-interactions/running-draft.expected.md index 5da9965d81..3cc09b5a76 100644 --- a/snapshots/web/live-interactions/running-draft.expected.md +++ b/snapshots/web/live-interactions/running-draft.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with a one-sentence description - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/message-actions/ui.expected.md b/snapshots/web/message-actions/ui.expected.md index 2ee34dea49..95a12947ea 100644 --- a/snapshots/web/message-actions/ui.expected.md +++ b/snapshots/web/message-actions/ui.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Use the read tool twice + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/minimal-compact/ui.expected.md b/snapshots/web/minimal-compact/ui.expected.md index ce3f77da98..9d48d2da0a 100644 --- a/snapshots/web/minimal-compact/ui.expected.md +++ b/snapshots/web/minimal-compact/ui.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": "Remember the project requirements: imple" - text: Minimal mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/minimal-preset/ui.expected.md b/snapshots/web/minimal-preset/ui.expected.md index 472927485d..3dc7e2f314 100644 --- a/snapshots/web/minimal-preset/ui.expected.md +++ b/snapshots/web/minimal-preset/ui.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Use the bash tool to - text: Minimal mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/minimal-read-image/ui.expected.md b/snapshots/web/minimal-read-image/ui.expected.md index ab1052525e..2ae95c7e0d 100644 --- a/snapshots/web/minimal-read-image/ui.expected.md +++ b/snapshots/web/minimal-read-image/ui.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Use read_image to inspect red.png. - text: Minimal mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/open-in-app-ssh/header.expected.md b/snapshots/web/open-in-app-ssh/header.expected.md index f3fafda508..e960ef3f6e 100644 --- a/snapshots/web/open-in-app-ssh/header.expected.md +++ b/snapshots/web/open-in-app-ssh/header.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Use the read tool twice + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/plan-review/approved-expanded.expected.md b/snapshots/web/plan-review/approved-expanded.expected.md index a1a5c163cb..0201f1e11d 100644 --- a/snapshots/web/plan-review/approved-expanded.expected.md +++ b/snapshots/web/plan-review/approved-expanded.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": "Plan a small change: add" - text: Standard mode + - button "Session panel" - button "More actions" - tablist: - tab "Chat" [selected] diff --git a/snapshots/web/plan-review/approved.expected.md b/snapshots/web/plan-review/approved.expected.md index 50c7bf0c88..6208b1aa67 100644 --- a/snapshots/web/plan-review/approved.expected.md +++ b/snapshots/web/plan-review/approved.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": "Plan a small change: add" - text: Standard mode + - button "Session panel" - button "More actions" - tablist: - tab "Chat" [selected] diff --git a/snapshots/web/present/ui.expected.md b/snapshots/web/present/ui.expected.md index 26a7e07dd0..1358b3f907 100644 --- a/snapshots/web/present/ui.expected.md +++ b/snapshots/web/present/ui.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Use one run_code program to - text: PTC mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/ptc-round/ui-ja.expected.md b/snapshots/web/ptc-round/ui-ja.expected.md index 74494139d7..11220e2a3a 100644 --- a/snapshots/web/ptc-round/ui-ja.expected.md +++ b/snapshots/web/ptc-round/ui-ja.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "セッション階層": "Using ONE run_code program: run" - text: PTC モード + - button "セッションパネル" - button "その他の操作" - button "右サイドバーを開く" - tablist: diff --git a/snapshots/web/ptc-round/ui.expected.md b/snapshots/web/ptc-round/ui.expected.md index f0fe4d20a3..a0fabcb8c1 100644 --- a/snapshots/web/ptc-round/ui.expected.md +++ b/snapshots/web/ptc-round/ui.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": "Using ONE run_code program: run" - text: PTC mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/question-composer/answered-expanded.expected.md b/snapshots/web/question-composer/answered-expanded.expected.md index 8b3e7c398e..8dff29824a 100644 --- a/snapshots/web/question-composer/answered-expanded.expected.md +++ b/snapshots/web/question-composer/answered-expanded.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Use the ask_user_question tool to - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/question-composer/answered.expected.md b/snapshots/web/question-composer/answered.expected.md index 5030acee5b..f3def13c95 100644 --- a/snapshots/web/question-composer/answered.expected.md +++ b/snapshots/web/question-composer/answered.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Use the ask_user_question tool to - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/question-composer/cancelled.expected.md b/snapshots/web/question-composer/cancelled.expected.md index b09fe00e55..29cb6d4186 100644 --- a/snapshots/web/question-composer/cancelled.expected.md +++ b/snapshots/web/question-composer/cancelled.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Use the ask_user_question tool to + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/question-composer/late-answered.expected.md b/snapshots/web/question-composer/late-answered.expected.md index 833cccd42c..752dc41523 100644 --- a/snapshots/web/question-composer/late-answered.expected.md +++ b/snapshots/web/question-composer/late-answered.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Use the ask_user_question tool to + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/question-composer/queued.expected.md b/snapshots/web/question-composer/queued.expected.md index abf6f1fe6a..1fb49f32ab 100644 --- a/snapshots/web/question-composer/queued.expected.md +++ b/snapshots/web/question-composer/queued.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Use the ask_user_question tool to + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/queue-actions/collapsed.expected.md b/snapshots/web/queue-actions/collapsed.expected.md index 272b71d385..cc35fe0bfe 100644 --- a/snapshots/web/queue-actions/collapsed.expected.md +++ b/snapshots/web/queue-actions/collapsed.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with a one-sentence description - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/queue-actions/editing.expected.md b/snapshots/web/queue-actions/editing.expected.md index 2fc14ac64d..98ce89344a 100644 --- a/snapshots/web/queue-actions/editing.expected.md +++ b/snapshots/web/queue-actions/editing.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with a one-sentence description - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/queue-actions/goal-stop.expected.md b/snapshots/web/queue-actions/goal-stop.expected.md index 92a11037e0..3bfd28417f 100644 --- a/snapshots/web/queue-actions/goal-stop.expected.md +++ b/snapshots/web/queue-actions/goal-stop.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Queue item to remove - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/queue-actions/layout.expected.md b/snapshots/web/queue-actions/layout.expected.md index b79770e640..ecf45f562a 100644 --- a/snapshots/web/queue-actions/layout.expected.md +++ b/snapshots/web/queue-actions/layout.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": workspace - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/queue-actions/preserved-expanded.expected.md b/snapshots/web/queue-actions/preserved-expanded.expected.md index 94d44ce9f8..776523a5d3 100644 --- a/snapshots/web/queue-actions/preserved-expanded.expected.md +++ b/snapshots/web/queue-actions/preserved-expanded.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with a one-sentence description - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/queue-actions/preserved.expected.md b/snapshots/web/queue-actions/preserved.expected.md index be4dd9d5ab..d32b1a15ea 100644 --- a/snapshots/web/queue-actions/preserved.expected.md +++ b/snapshots/web/queue-actions/preserved.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with a one-sentence description - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/queue-actions/sending.expected.md b/snapshots/web/queue-actions/sending.expected.md index 0ce88945b0..6bb686eef7 100644 --- a/snapshots/web/queue-actions/sending.expected.md +++ b/snapshots/web/queue-actions/sending.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with a one-sentence description - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/queue-actions/ui.expected.md b/snapshots/web/queue-actions/ui.expected.md index 07b3fa10d5..f7e6e50b4f 100644 --- a/snapshots/web/queue-actions/ui.expected.md +++ b/snapshots/web/queue-actions/ui.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with a one-sentence description - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/queued-image/delivered.expected.md b/snapshots/web/queued-image/delivered.expected.md index 5fa41f79e6..d855368d94 100644 --- a/snapshots/web/queued-image/delivered.expected.md +++ b/snapshots/web/queued-image/delivered.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with a one-sentence description - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/queued-image/queued.expected.md b/snapshots/web/queued-image/queued.expected.md index 4f5cdbcf4e..6f63c63ac0 100644 --- a/snapshots/web/queued-image/queued.expected.md +++ b/snapshots/web/queued-image/queued.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Reply with a one-sentence description - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/rich-text-quotes/ui.expected.md b/snapshots/web/rich-text-quotes/ui.expected.md index f7e0c3a26f..8e9d4fd3e0 100644 --- a/snapshots/web/rich-text-quotes/ui.expected.md +++ b/snapshots/web/rich-text-quotes/ui.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Quote history + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/seeded-history/command-row.expected.md b/snapshots/web/seeded-history/command-row.expected.md index c8f5bab631..dcf6118c23 100644 --- a/snapshots/web/seeded-history/command-row.expected.md +++ b/snapshots/web/seeded-history/command-row.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Use the read tool twice + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/seeded-history/feedback-row.expected.md b/snapshots/web/seeded-history/feedback-row.expected.md index 0d8fedec6e..06a37daa66 100644 --- a/snapshots/web/seeded-history/feedback-row.expected.md +++ b/snapshots/web/seeded-history/feedback-row.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Use the read tool twice + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/seeded-history/ui-expanded.expected.md b/snapshots/web/seeded-history/ui-expanded.expected.md index 12f6c4d0cd..39c1b38b0f 100644 --- a/snapshots/web/seeded-history/ui-expanded.expected.md +++ b/snapshots/web/seeded-history/ui-expanded.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Use the read tool twice + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/seeded-history/ui.expected.md b/snapshots/web/seeded-history/ui.expected.md index 794fa8fad2..96227b6799 100644 --- a/snapshots/web/seeded-history/ui.expected.md +++ b/snapshots/web/seeded-history/ui.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Use the read tool twice + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/skill-tool-row/ui.expected.md b/snapshots/web/skill-tool-row/ui.expected.md index cd974f8a45..b217a3071b 100644 --- a/snapshots/web/skill-tool-row/ui.expected.md +++ b/snapshots/web/skill-tool-row/ui.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Load the editing-cordis-compositions ski + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/steering/mid-steer.expected.md b/snapshots/web/steering/mid-steer.expected.md index ccb5f7bae1..f445dafc6a 100644 --- a/snapshots/web/steering/mid-steer.expected.md +++ b/snapshots/web/steering/mid-steer.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Use the ask_user_question tool to - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/steering/settled-expanded.expected.md b/snapshots/web/steering/settled-expanded.expected.md index 7841c63d07..facc318243 100644 --- a/snapshots/web/steering/settled-expanded.expected.md +++ b/snapshots/web/steering/settled-expanded.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Use the ask_user_question tool to - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/steering/settled.expected.md b/snapshots/web/steering/settled.expected.md index a463df9054..b606292abe 100644 --- a/snapshots/web/steering/settled.expected.md +++ b/snapshots/web/steering/settled.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Use the ask_user_question tool to - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/steering/trajectory.expected.md b/snapshots/web/steering/trajectory.expected.md index 2bbaa871a0..d753c24598 100644 --- a/snapshots/web/steering/trajectory.expected.md +++ b/snapshots/web/steering/trajectory.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Use the ask_user_question tool to - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/subagent-conversation/nested.expected.md b/snapshots/web/subagent-conversation/nested.expected.md index 2d68bf7341..907cdb2a34 100644 --- a/snapshots/web/subagent-conversation/nested.expected.md +++ b/snapshots/web/subagent-conversation/nested.expected.md @@ -5,6 +5,7 @@ - 'button "Switch subagent: event-sourcing researcher"': event-sourcing researcher - text: / - 'button "Switch subagent: example editor"': example editor + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/subagent-conversation/ui-expanded.expected.md b/snapshots/web/subagent-conversation/ui-expanded.expected.md index fb99690fa6..f96afdc2e1 100644 --- a/snapshots/web/subagent-conversation/ui-expanded.expected.md +++ b/snapshots/web/subagent-conversation/ui-expanded.expected.md @@ -5,6 +5,7 @@ - 'button "Switch subagent: event-sourcing researcher"': event-sourcing researcher - button "1 subagent" - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/subagent-conversation/ui.expected.md b/snapshots/web/subagent-conversation/ui.expected.md index df0bf918eb..5311790493 100644 --- a/snapshots/web/subagent-conversation/ui.expected.md +++ b/snapshots/web/subagent-conversation/ui.expected.md @@ -5,6 +5,7 @@ - 'button "Switch subagent: event-sourcing researcher"': event-sourcing researcher - button "1 subagent" - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/subagent-interrupt/image-queue.expected.md b/snapshots/web/subagent-interrupt/image-queue.expected.md index ea14ddcc39..bd9f9fb6e8 100644 --- a/snapshots/web/subagent-interrupt/image-queue.expected.md +++ b/snapshots/web/subagent-interrupt/image-queue.expected.md @@ -4,6 +4,7 @@ - text: / - 'button "Switch subagent: event-sourcing researcher"': event-sourcing researcher - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/subagent-interrupt/offline-composer.expected.md b/snapshots/web/subagent-interrupt/offline-composer.expected.md index f2b066b262..749a55388c 100644 --- a/snapshots/web/subagent-interrupt/offline-composer.expected.md +++ b/snapshots/web/subagent-interrupt/offline-composer.expected.md @@ -4,6 +4,7 @@ - text: / - 'button "Switch subagent: event-sourcing researcher"': event-sourcing researcher - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/turn-tail-actions/completed.expected.md b/snapshots/web/turn-tail-actions/completed.expected.md index 75da70b7bc..5030f76a04 100644 --- a/snapshots/web/turn-tail-actions/completed.expected.md +++ b/snapshots/web/turn-tail-actions/completed.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Begin your reply with the - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/turn-tail-actions/focused.expected.md b/snapshots/web/turn-tail-actions/focused.expected.md index b25518c55a..6976d8c922 100644 --- a/snapshots/web/turn-tail-actions/focused.expected.md +++ b/snapshots/web/turn-tail-actions/focused.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Begin your reply with the - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/turn-tail-actions/running.expected.md b/snapshots/web/turn-tail-actions/running.expected.md index e4834f582a..dd8eb4972e 100644 --- a/snapshots/web/turn-tail-actions/running.expected.md +++ b/snapshots/web/turn-tail-actions/running.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Begin your reply with the - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/turn-tail-actions/settled.expected.md b/snapshots/web/turn-tail-actions/settled.expected.md index 361f60047a..3f887c7efd 100644 --- a/snapshots/web/turn-tail-actions/settled.expected.md +++ b/snapshots/web/turn-tail-actions/settled.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Begin your reply with the - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/turn-tail-actions/usage-expanded.expected.md b/snapshots/web/turn-tail-actions/usage-expanded.expected.md index 4495ac7acc..ea6ed847d6 100644 --- a/snapshots/web/turn-tail-actions/usage-expanded.expected.md +++ b/snapshots/web/turn-tail-actions/usage-expanded.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Begin your reply with the - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/snapshots/web/web-search-round/ui.expected.md b/snapshots/web/web-search-round/ui.expected.md index 33b37f5230..29ace54a57 100644 --- a/snapshots/web/web-search-round/ui.expected.md +++ b/snapshots/web/web-search-round/ui.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Use web_search once with queries - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: From 0cf96191623ec0dd1587f9162144fab3e2fc060f Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 6 Nov 2026 11:48:35 +0800 Subject: [PATCH 024/404] fix(panel): draw Session panel section titles in the primary text color Section titles now read as headings in the primary text color, apart from the secondary values and counts beside and below them. --- .../client/ui-session-panel/src/client/SessionPanel.module.css | 2 +- 1 file changed, 1 insertion(+), 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 8bd6ca6fa8..76e9a414b6 100644 --- a/packages/client/ui-session-panel/src/client/SessionPanel.module.css +++ b/packages/client/ui-session-panel/src/client/SessionPanel.module.css @@ -65,7 +65,7 @@ min-width: 0; margin: 0; overflow: hidden; - color: var(--dsw-alias-label-tertiary); + color: var(--dsw-alias-label-primary); font: var(--dsw-font-xxs-12); text-overflow: ellipsis; white-space: nowrap; From 7da52786539bd353b52de640226a1736d27ddc25 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 6 Nov 2026 12:10:29 +0800 Subject: [PATCH 025/404] feat(panel): highlight Session panel rows as a whole and reveal row menus PanelRow gains a menu slot for row actions such as a More button, shown on row hover, on focus inside the row, and while its menu is open, and always without hover. A row with an action covers its whole width with the action's button, and any row with an action or row actions fills as a whole on hover and while one of its menus stays open, instead of filling only the icon and text. The project row moves its More button into the menu slot. --- .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 2 +- packages/client/ui-primitives/README.zh.md | 2 +- .../ui-primitives/src/PanelRow.module.css | 70 +++++++++++++++---- .../client/ui-primitives/src/PanelRow.tsx | 20 ++++-- .../tests/panel-row.client.spec.tsx | 14 ++++ .../client/ui-session-panel/README.i18n.yaml | 4 +- packages/client/ui-session-panel/README.md | 2 +- packages/client/ui-session-panel/README.zh.md | 2 +- .../src/client/ProjectRow.module.css | 12 ---- .../src/client/ProjectRow.tsx | 6 +- 11 files changed, 93 insertions(+), 45 deletions(-) delete mode 100644 packages/client/ui-session-panel/src/client/ProjectRow.module.css diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 50f2f4ff45..118b190de7 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: 57f5e3f2dc9eb425 - zh: 4159654b2604ec5d + en: f23ddcee7e3eeb18 + zh: 2afbd08ebfa4247c /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 1fcc1a9fc1..7807d24512 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -55,7 +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. | +| `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. `menu` holds row actions, such as a More button, after the trailing area; they show on row hover, on focus inside the row, and while one has its menu open, and always without hover. `onActivate` makes the whole row one button while the trailing area and the menu stay separate controls; a row with an action or row actions fills as a whole on hover and while one of its menus is open. 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 656811f72b..fd803dbaaa 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -55,7 +55,7 @@ kind: "package-library" | `SegmentedTabs` | 受控的等宽分段标签,支持滑动指示条及左/右方向键、Home、End 导航。调用方提供文案、标签与面板 id,以及面板内容。默认 `size="md"` 总高 42px、内边距 4px;`size="sm"` 总高 34px、内边距 2px。 | | `Tag` | 只读胶囊徽章;`tone` 选择八种配色之一。 | | `PathLabel` | 单行文件路径:目录使用弱化颜色,文件名使用主色,悬停可查看完整路径。空间足够时靠左显示;溢出时保留尾部并在左侧渐隐,路径或尺寸变化时更新。 | -| `PanelRow` | 摘要面板中的一行事实:16px 装饰图标、单行内容(溢出时以省略号截断)以及可选的尾部数值或控件。图标沿用行文字颜色。传入 `onActivate` 时,图标与内容成为同一个按钮,带悬停与按下填充,尾部区域留在按钮之外;其余属性(例如右键菜单触发属性)落在外层元素上。 | +| `PanelRow` | 摘要面板中的一行事实:16px 装饰图标、单行内容(溢出时以省略号截断)以及可选的尾部数值或控件。图标沿用行文字颜色。`menu` 放在尾部区域之后的行操作(例如「更多」按钮):鼠标悬停在行上、焦点在行内或其菜单打开时显示,没有悬停能力的设备上始终显示。传入 `onActivate` 时整行成为一个按钮,尾部区域与 `menu` 仍是各自独立的控件;带操作或行操作的行在悬停时以及菜单打开期间整行填充。其余属性(例如右键菜单触发属性)落在外层元素上。 | | `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 index 4a6c786fd8..58a6686aba 100644 --- a/packages/client/ui-primitives/src/PanelRow.module.css +++ b/packages/client/ui-primitives/src/PanelRow.module.css @@ -1,11 +1,18 @@ -/* 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. */ +/* One summary-panel fact: [16px icon] gap 8 [content 13/28] [trailing] [menu]. + The icon inherits the row ink so a fact and its glyph share one foreground. + A row with an action or row actions highlights as a whole; the action's + button covers the row, and the trailing area and menu sit above it. */ .row { + position: relative; display: flex; align-items: center; gap: 4px; + box-sizing: border-box; min-width: 0; + min-height: 28px; + padding: 0 6px; + border-radius: var(--dsw-radius-sm); color: var(--dsw-alias-label-primary); font: var(--dsw-font-xs-13); } @@ -15,15 +22,13 @@ 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; + padding: 0; border: 0; color: inherit; background: transparent; @@ -32,18 +37,19 @@ cursor: pointer; } -@media (hover: hover) { - .action:hover { - background: var(--dsw-alias-interactive-bg-hover); - } -} - -.action:active { - background: var(--dsw-alias-interactive-bg-active); +.action::after { + position: absolute; + inset: 0; + border-radius: inherit; + content: ''; } .action:focus-visible { - outline-style: solid; + outline: none; +} + +.row:has(> .action:focus-visible) { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); outline-offset: -2px; } @@ -69,10 +75,44 @@ white-space: nowrap; } -.trailing { +.trailing, +.menu { + position: relative; + z-index: 1; display: inline-flex; flex: none; align-items: center; gap: 4px; +} + +.trailing { color: var(--dsw-alias-label-tertiary); } + +@media (hover: hover) { + .interactive:hover { + background: var(--dsw-alias-interactive-bg-hover); + } + + .menu { + opacity: 0; + } + + .row:hover .menu, + .row:focus-within .menu { + opacity: 1; + } +} + +/* An open menu keeps its row highlighted and its trigger visible after the pointer leaves for the menu. */ +.interactive:has([aria-expanded='true']) { + background: var(--dsw-alias-interactive-bg-hover); +} + +.menu:has([aria-expanded='true']) { + opacity: 1; +} + +.interactive:has(> .action:active) { + background: var(--dsw-alias-interactive-bg-active); +} diff --git a/packages/client/ui-primitives/src/PanelRow.tsx b/packages/client/ui-primitives/src/PanelRow.tsx index a93fb95bf4..2a2800fb2c 100644 --- a/packages/client/ui-primitives/src/PanelRow.tsx +++ b/packages/client/ui-primitives/src/PanelRow.tsx @@ -13,28 +13,38 @@ export interface PanelRowProps extends Omit, 'childr 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. */ + /** + * Row actions after the trailing area, such as a More button. They show + * while the pointer is over the row, focus is inside it, or one of them has + * its menu open, and always on devices without hover. + */ + readonly menu?: ReactNode + /** Make the whole row one button with this action; the trailing area and the menu stay separate controls above 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. + * Render one summary-panel row: icon, single-line content, an optional + * trailing area, and optional row actions. A row with an action or row + * actions highlights as a whole on hover and while one of its menus is open. + * @param props - row content, the optional action and row actions, and attributes for the outer element. * @returns the row element. */ -export function PanelRow({ icon, children, trailing, onActivate, className, ...attributes }: PanelRowProps) { +export function PanelRow({ icon, children, trailing, menu, onActivate, className, ...attributes }: PanelRowProps) { const body = ( <> {children} ) + const interactive = onActivate !== undefined || menu !== undefined return ( -
+
{onActivate === undefined ? {body} : } {trailing !== undefined && {trailing}} + {menu !== undefined && {menu}}
) } diff --git a/packages/client/ui-primitives/tests/panel-row.client.spec.tsx b/packages/client/ui-primitives/tests/panel-row.client.spec.tsx index 7a7b28f497..b5c1435e04 100644 --- a/packages/client/ui-primitives/tests/panel-row.client.spec.tsx +++ b/packages/client/ui-primitives/tests/panel-row.client.spec.tsx @@ -29,6 +29,20 @@ describe('PanelRow', () => { expect(onActivate).toHaveBeenCalledTimes(1) }) + it('places row actions after the trailing area and marks only rows with an action or row actions as interactive', () => { + const view = render( + } trailing={value} menu={}>Project, + ) + const row = view.container.querySelector('[data-panel-row]') as HTMLElement + expect([...row.children].map(child => child.textContent)).toEqual(['Project', 'value', 'More']) + const interactive = row.className + cleanup() + const plain = render(} trailing={value}>Project) + const staticRow = plain.container.querySelector('[data-panel-row]') as HTMLElement + expect(staticRow.children).toHaveLength(2) + expect(staticRow.className).not.toBe(interactive) + }) + 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) diff --git a/packages/client/ui-session-panel/README.i18n.yaml b/packages/client/ui-session-panel/README.i18n.yaml index c93e04fcc3..0d5adc4dd8 100644 --- a/packages/client/ui-session-panel/README.i18n.yaml +++ b/packages/client/ui-session-panel/README.i18n.yaml @@ -21,8 +21,8 @@ en: 1d99ccdba0457d10 zh: 81833d87548d3225 /deepseek-ai-dsh-client-ui-session-panel/use-this-package/contribute-a-section: - en: 3e9463ce11beff16 - zh: d10d474c06afa3ca + en: 46c0aa93bceeaf0d + zh: 478acadcd8828db6 /deepseek-ai-dsh-client-ui-session-panel/understand-the-implementation: en: e59cf3dc6b08e893 zh: 33548291a59090c2 diff --git a/packages/client/ui-session-panel/README.md b/packages/client/ui-session-panel/README.md index b8d1ee4f87..f0ce954d68 100644 --- a/packages/client/ui-session-panel/README.md +++ b/packages/client/ui-session-panel/README.md @@ -42,7 +42,7 @@ Plugins share a title by registering rows in a section owner's row slot. The bui 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. +Summary rows from every package use the `PanelRow` primitive, so icon, text, and trailing areas line up across sections; put a row's More button in its `menu` so every row highlights as a whole and reveals its actions the same way. ----- diff --git a/packages/client/ui-session-panel/README.zh.md b/packages/client/ui-session-panel/README.zh.md index b2e8b394bf..86b6f8b12c 100644 --- a/packages/client/ui-session-panel/README.zh.md +++ b/packages/client/ui-session-panel/README.zh.md @@ -42,7 +42,7 @@ kind: "package-reference" 面板隐藏时也要可见的标记(例如需要处理的红点)放进 `conversation.session.panel.indicator` 列表。每个占位都带有说明自身的文字,这些文字会成为开关无障碍名称的一部分。 -各包的摘要行都使用 `PanelRow` 原语,使不同分栏的图标、文字与尾部区域对齐。 +各包的摘要行都使用 `PanelRow` 原语,使不同分栏的图标、文字与尾部区域对齐;行的「更多」按钮放进它的 `menu`,各行就以同样的方式整行高亮并显示操作。 ----- diff --git a/packages/client/ui-session-panel/src/client/ProjectRow.module.css b/packages/client/ui-session-panel/src/client/ProjectRow.module.css deleted file mode 100644 index e4561fd1da..0000000000 --- a/packages/client/ui-session-panel/src/client/ProjectRow.module.css +++ /dev/null @@ -1,12 +0,0 @@ -/* 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 index 9381ce1945..b0920175bf 100644 --- a/packages/client/ui-session-panel/src/client/ProjectRow.tsx +++ b/packages/client/ui-session-panel/src/client/ProjectRow.tsx @@ -3,7 +3,6 @@ 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 @@ -25,11 +24,8 @@ export function ProjectRow({ return ( } - trailing={renderFactorySlot('contextMenu.button', { - target, label: t('project.actions'), className: css.more, size: 'sm', - })} + menu={renderFactorySlot('contextMenu.button', { target, label: t('project.actions'), size: 'sm' })} data-session-panel-project="" > From 5286026ec52247d7b01462a6efab112adac8e421 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 6 Nov 2026 12:56:56 +0800 Subject: [PATCH 026/404] fix(panel): draw section titles in secondary ink at medium weight Primary-ink titles read as one more row of content. Secondary ink at medium weight sets them apart from the primary rows below and from the tertiary counts and progress beside them. --- .../ui-session-panel/src/client/SessionPanel.module.css | 4 +++- 1 file changed, 3 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 76e9a414b6..2a66ada038 100644 --- a/packages/client/ui-session-panel/src/client/SessionPanel.module.css +++ b/packages/client/ui-session-panel/src/client/SessionPanel.module.css @@ -60,13 +60,15 @@ padding: 0 6px; } +/* Secondary ink at medium weight: apart from the primary rows below and the tertiary counts beside it. */ .title { flex: 1 1 auto; min-width: 0; margin: 0; overflow: hidden; - color: var(--dsw-alias-label-primary); + color: var(--dsw-alias-label-secondary); font: var(--dsw-font-xxs-12); + font-weight: 500; text-overflow: ellipsis; white-space: nowrap; } From ac96c518fb2de7f4700db38531533f1815147164 Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 6 Nov 2026 16:31:24 +0800 Subject: [PATCH 027/404] ci(preview): publish a snapshot diff page with each PR preview Co-authored-by: yudshj <16971372+yudshj@users.noreply.github.com> --- .../workflows/build-preview-cloudflare.yml | 32 ++- scripts/preview-workflow.spec.ts | 14 +- scripts/snapshot-diff-page.spec.ts | 76 ++++++ scripts/snapshot-diff-page.ts | 223 ++++++++++++++++++ 4 files changed, 333 insertions(+), 12 deletions(-) create mode 100644 scripts/snapshot-diff-page.spec.ts create mode 100644 scripts/snapshot-diff-page.ts diff --git a/.github/workflows/build-preview-cloudflare.yml b/.github/workflows/build-preview-cloudflare.yml index 5625d75a9c..c8cb718234 100644 --- a/.github/workflows/build-preview-cloudflare.yml +++ b/.github/workflows/build-preview-cloudflare.yml @@ -43,9 +43,12 @@ jobs: || 'ubuntu-24.04' }} name: cloudflare pages preview steps: + # The pull_request checkout is the merge commit; depth 2 brings its first + # parent, the base branch tip, for the snapshot diff page. - uses: actions/checkout@v7.0.1 with: persist-credentials: false + fetch-depth: 2 - uses: pnpm/action-setup@v5.0.0 with: @@ -98,6 +101,11 @@ jobs: find apps/web/dist -name '*.map' -delete cp apps/web/dist/preview.html apps/web/dist/index.html + # Reviewers read snapshot changes at /snapshot-diff/, which opens on the + # SDK blank-Session catalog (system prompt and tool schemas). + - name: Render the snapshot diff page + run: pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD --out apps/web/dist/snapshot-diff/index.html + - name: Upload to Cloudflare Pages id: upload continue-on-error: true @@ -164,7 +172,8 @@ jobs: # The alias URL follows from the pull request number, so it is stable # across redeploys and worth stating once. The marker makes the comment # idempotent: a pull request opened before this workflow existed never - # sees an `opened` event, and every later push must not restate the URL. + # sees an `opened` event, and every later push must not restate the URL; + # an existing comment with older text is edited in place. - name: Comment the preview URL id: comment continue-on-error: true @@ -173,18 +182,21 @@ jobs: PR: ${{ github.event.pull_request.number }} run: | marker='' - existing=$(gh pr view "$PR" --json comments \ - --jq "[.comments[] | select(.body | contains(\"$marker\")) | .url] | first // empty") - if [ -n "$existing" ]; then - echo "preview URL already commented: $existing" - exit 0 - fi + url="https://pr-$PR.${CF_PROJECT}.pages.dev" # The marker sits on its own line: markdown renders no link on a # line that opens with a raw HTML comment. - printf '%s\n\n%s\n' \ + body=$(printf '%s\n\n%s\n' \ "$marker" \ - "[Preview for #$PR](https://pr-$PR.${CF_PROJECT}.pages.dev) (requires Cloudflare Access sign-in)" \ - | gh pr comment "$PR" --body-file - + "[Preview for #$PR]($url) · [snapshot changes]($url/snapshot-diff/) (requires Cloudflare Access sign-in)") + existing=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR/comments" --paginate \ + --jq "[.[] | select(.body | contains(\"$marker\"))] | first // empty | [.id, .body] | @json") + if [ -z "$existing" ]; then + printf '%s\n' "$body" | gh pr comment "$PR" --body-file - + elif [ "$(jq -r '.[1]' <<< "$existing")" != "$body" ]; then + gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$(jq -r '.[0]' <<< "$existing")" -f body="$body" > /dev/null + else + echo "preview URL already commented" + fi # Publishing stays outside the required verdict: a Cloudflare, Access, or # comment failure warns, while a build failure still fails this check. diff --git a/scripts/preview-workflow.spec.ts b/scripts/preview-workflow.spec.ts index e38f18b776..bd21bc2c0a 100644 --- a/scripts/preview-workflow.spec.ts +++ b/scripts/preview-workflow.spec.ts @@ -25,12 +25,12 @@ describe('PR preview workflow', () => { expect(preview['runs-on']).toContain('DSH_CI_FAILOVER_LINUX') expect(workflow.on).toEqual({ pull_request: { types: ['opened', 'synchronize', 'reopened'] } }) expect(workflow.permissions).toEqual({ contents: 'read', 'pull-requests': 'write' }) - expect(preview.steps.find(step => step.uses === 'actions/checkout@v7.0.1')?.with).toEqual({ 'persist-credentials': false }) + expect(preview.steps.find(step => step.uses === 'actions/checkout@v7.0.1')?.with).toEqual({ 'persist-credentials': false, 'fetch-depth': 2 }) }) it('fails the check only for build failures and warns about publication', () => { const byName = (name: string) => preview.steps.find(step => step.name === name) - for (const name of ['Build workspace and check aggregate programs', 'Build the preview page and pack the VFS image', 'Shape the upload']) { + for (const name of ['Build workspace and check aggregate programs', 'Build the preview page and pack the VFS image', 'Shape the upload', 'Render the snapshot diff page']) { expect(byName(name)?.['continue-on-error'], `${name} must stay blocking`).toBeUndefined() } for (const name of ['Upload to Cloudflare Pages', 'Verify the protected deployment serves the image', 'Comment the preview URL']) { @@ -79,5 +79,15 @@ describe('PR preview workflow', () => { const comment = preview.steps.find(step => step.name === 'Comment the preview URL')! expect(comment.run).toContain('') expect(comment.run).toContain('gh pr comment "$PR" --body-file -') + expect(comment.run).toContain('[snapshot changes]($url/snapshot-diff/)') + expect(comment.run).toContain('gh api -X PATCH') + }) + + it('renders the snapshot diff page into the upload against the base branch tip', () => { + const steps = preview.steps.map(step => step.name) + const page = preview.steps.find(step => step.name === 'Render the snapshot diff page')! + expect(page.run).toBe('pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD --out apps/web/dist/snapshot-diff/index.html') + expect(steps.indexOf('Render the snapshot diff page')).toBeGreaterThan(steps.indexOf('Shape the upload')) + expect(steps.indexOf('Render the snapshot diff page')).toBeLessThan(steps.indexOf('Upload to Cloudflare Pages')) }) }) diff --git a/scripts/snapshot-diff-page.spec.ts b/scripts/snapshot-diff-page.spec.ts new file mode 100644 index 0000000000..5147ec6dd0 --- /dev/null +++ b/scripts/snapshot-diff-page.spec.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from 'vitest' +import { groupDiffs, parseUnifiedDiff, renderSnapshotDiffPage } from './snapshot-diff-page.ts' + +const limits = { fileLines: 100, totalChars: 10_000 } + +const diff = `diff --git a/snapshots/sdk/text-turn/system-prompt.expected.md b/snapshots/sdk/text-turn/system-prompt.expected.md +index 1111111..2222222 100644 +--- a/snapshots/sdk/text-turn/system-prompt.expected.md ++++ b/snapshots/sdk/text-turn/system-prompt.expected.md +@@ -1,2 +1,2 @@ + You are an agent. +-Old rule. ++New rule. +diff --git a/snapshots/web/ptc-round/session.jsonl b/snapshots/web/ptc-round/session.jsonl +deleted file mode 100644 +index 3333333..0000000 +--- a/snapshots/web/ptc-round/session.jsonl ++++ /dev/null +@@ -1 +0,0 @@ +-{"type":"header"} +diff --git a/snapshots/web/ptc-round/image.png b/snapshots/web/ptc-round/image.png +new file mode 100644 +index 0000000..4444444 +Binary files /dev/null and b/snapshots/web/ptc-round/image.png differ +diff --git a/snapshots/web/present/workspace.expected/a b/说明.txt b/snapshots/web/present/workspace.expected/a b/说明.txt +old mode 100644 +new mode 100755 +` + +const catalog = ['snapshots/sdk/text-turn/system-prompt.expected.md', 'snapshots/session/text-turn/tool-schemas.expected.json'] + +describe('snapshot diff page', () => { + it('splits git diff output into files with their hunks', () => { + expect(parseUnifiedDiff(diff, limits)).toEqual([ + { path: 'snapshots/sdk/text-turn/system-prompt.expected.md', hunks: '@@ -1,2 +1,2 @@\n You are an agent.\n-Old rule.\n+New rule.', binary: false, omitted: 0 }, + { path: 'snapshots/web/ptc-round/session.jsonl', hunks: '@@ -1 +0,0 @@\n-{"type":"header"}', binary: false, omitted: 0 }, + { path: 'snapshots/web/ptc-round/image.png', hunks: '', binary: true, omitted: 0 }, + { path: 'snapshots/web/present/workspace.expected/a b/说明.txt', hunks: '', binary: false, omitted: 0 }, + ]) + expect(parseUnifiedDiff('', limits)).toEqual([]) + }) + + it('rejects paths git still quotes', () => { + expect(() => parseUnifiedDiff('diff --git "a/snapshots/x\\ty" "b/snapshots/x\\ty"\n', limits)).toThrow('unsupported quoted path') + }) + + it('truncates long files and drops hunks once the total budget is spent', () => { + const section = (name: string, lines: number) => `diff --git a/${name} b/${name}\n--- a/${name}\n+++ b/${name}\n@@ -1,${lines} +1,${lines} @@\n${'+x\n'.repeat(lines - 1)}` + const [long, fits, over] = parseUnifiedDiff(section('a', 150) + section('b', 10) + section('c', 10), { fileLines: 100, totalChars: 365 }) + expect([long!.hunks.split('\n').length, long!.omitted]).toEqual([100, 50]) + expect([fits!.hunks.split('\n').length, fits!.omitted]).toEqual([10, 0]) + expect([over!.hunks, over!.omitted]).toEqual(['', 10]) + }) + + it('opens on the catalog, listing unchanged catalog files, then groups by scenario', () => { + const groups = groupDiffs(parseUnifiedDiff(diff, limits).slice(0, 3), catalog) + expect(groups.map(group => [group.title, group.paths, group.files.map(file => file.path)])).toEqual([ + ['SDK blank Session catalog', catalog, ['snapshots/sdk/text-turn/system-prompt.expected.md']], + ['sdk/text-turn', ['snapshots/sdk/text-turn/system-prompt.expected.md'], ['snapshots/sdk/text-turn/system-prompt.expected.md']], + ['web/ptc-round', ['snapshots/web/ptc-round/image.png', 'snapshots/web/ptc-round/session.jsonl'], ['snapshots/web/ptc-round/image.png', 'snapshots/web/ptc-round/session.jsonl']], + ]) + }) + + it('lists a path once when a type change splits it into two sections', () => { + const removed = { path: 'snapshots/acp/cancel/system-prompt.expected.md', hunks: '@@ -1 +0,0 @@\n-../x', binary: false, omitted: 0 } + const added = { ...removed, hunks: '@@ -0,0 +1 @@\n+text' } + expect(groupDiffs([removed, added], catalog)[1]).toEqual({ title: 'acp/cancel', paths: [removed.path], files: [removed, added] }) + }) + + it('embeds the data so diff text cannot close the script element', () => { + const page = renderSnapshotDiffPage([{ title: 't', paths: ['p'], files: [{ path: 'p', hunks: '+', binary: false, omitted: 0 }] }], 'a → b') + expect(page).not.toContain('') + const data = /', binary: false, omitted: 0 }] }], heading: 'a → b' }) + }) +}) diff --git a/scripts/snapshot-diff-page.ts b/scripts/snapshot-diff-page.ts new file mode 100644 index 0000000000..e4f6bbdc96 --- /dev/null +++ b/scripts/snapshot-diff-page.ts @@ -0,0 +1,223 @@ +/** + * Renders the PR preview's snapshot diff page: one self-contained HTML file + * listing every changed file under `snapshots/` between two revisions, grouped + * by scenario directory. The page opens on the SDK blank-Session catalog, the + * system prompt and tool schemas the `sdk/text-turn` scenario's first request + * carries, and shows "No change" when neither file changed. + * + * Usage: `tsx scripts/snapshot-diff-page.ts --base --head --out ` + */ +import { execFileSync } from 'node:child_process' +import { mkdirSync, writeFileSync } from 'node:fs' +import { dirname } from 'node:path' +import { parseArgs } from 'node:util' +import * as yaml from 'js-yaml' + +/** Scenario whose first request represents a blank SDK Session. */ +const CATALOG_SCENARIO = 'snapshots/sdk/text-turn' + +/** Per-file and total limits on embedded diff text; the page notes what it omits. */ +export interface DiffLimits { + readonly fileLines: number + readonly totalChars: number +} + +/** Keeps the page well under the Cloudflare Pages 25 MiB per-file limit and responsive in a browser. */ +const LIMITS: DiffLimits = { fileLines: 2000, totalChars: 8_000_000 } + +/** One `diff --git` section: a changed file and its unified diff text. */ +export interface FileDiff { + /** Repository-relative path. */ + readonly path: string + /** Unified diff lines from the first `@@` hunk header, empty for binary or mode-only changes. */ + readonly hunks: string + /** True when git reports a binary change. */ + readonly binary: boolean + /** Hunk lines left out of `hunks` by the limits. */ + readonly omitted: number +} + +/** A selectable group of file diffs on the page. */ +export interface DiffGroup { + readonly title: string + /** Distinct paths the group covers, including unchanged ones. */ + readonly paths: readonly string[] + readonly files: readonly FileDiff[] +} + +/** + * Splits git diff output into per-file sections. + * @param text - Output of `git -c core.quotePath=false diff --no-color --no-renames`; + * a path git still quotes (one with `"`, `\\`, or a control character) is rejected. + * @param limits - Lines kept per file and characters kept across all files. + * @returns One entry per `diff --git` section, in output order. A path that + * changes between symlink and regular file has two sections. + */ +export function parseUnifiedDiff(text: string, limits: DiffLimits = LIMITS): FileDiff[] { + const files: FileDiff[] = [] + let budget = limits.totalChars + for (const section of text.split(/^(?=diff --git )/m)) { + if (!section.startsWith('diff --git ')) continue + const lines = section.split('\n') + // Without renames the header is `diff --git a/ b/` with both paths equal. + const header = section.slice('diff --git '.length, section.indexOf('\n') === -1 ? undefined : section.indexOf('\n')) + if (header.startsWith('"')) throw new Error(`unsupported quoted path in git diff header: ${header}`) + const path = header.slice('a/'.length, (header.length - ' '.length) / 2) + const hunkStart = lines.findIndex(line => line.startsWith('@@')) + const all = hunkStart === -1 ? [] : lines.slice(hunkStart, lines.at(-1) === '' ? -1 : undefined) + let kept = all.slice(0, limits.fileLines) + let hunks = kept.join('\n') + if (hunks.length > budget) { + kept = [] + hunks = '' + } + budget -= hunks.length + files.push({ path, hunks, binary: lines.some(line => line.startsWith('Binary files ')), omitted: all.length - kept.length }) + } + return files +} + +/** + * Groups changed files for the page: the catalog first, then one group per + * scenario directory (`snapshots//`) in path order. + * @param files - Changed files under `snapshots/`. + * @param catalogPaths - Files that make up the SDK blank-Session catalog. + * @returns The catalog group followed by the scenario groups. + */ +export function groupDiffs(files: readonly FileDiff[], catalogPaths: readonly string[]): DiffGroup[] { + const scenarios = new Map() + for (const file of [...files].sort((a, b) => a.path.localeCompare(b.path))) { + const key = file.path.split('/').slice(0, 3).join('/') + scenarios.set(key, [...scenarios.get(key) ?? [], file]) + } + return [ + { title: 'SDK blank Session catalog', paths: catalogPaths, files: files.filter(file => catalogPaths.includes(file.path)) }, + ...[...scenarios].map(([key, group]) => ({ title: key.replace(/^snapshots\//, ''), paths: [...new Set(group.map(file => file.path))], files: group })), + ] +} + +/** + * Renders the self-contained page. + * @param groups - Groups from {@link groupDiffs}; the first one opens by default. + * @param heading - Revision description shown under the title. + * @returns HTML text. + */ +export function renderSnapshotDiffPage(groups: readonly DiffGroup[], heading: string): string { + const data = JSON.stringify({ groups, heading }).replace(/ + + + + +Snapshot changes + + + + +
+ + + + +` +} + +/** + * Reads the catalog files from the catalog scenario's `snapshot.yml`. + * @param rev - Revision to read. + * @returns The system prompt sidecar and the tool schema sidecar, which lives + * in the scenario named by `header.toolSchemasSource` when present. + */ +function catalogPaths(rev: string): string[] { + const spec = yaml.load(git('show', `${rev}:${CATALOG_SCENARIO}/snapshot.yml`), { schema: yaml.JSON_SCHEMA }) as { header?: { toolSchemasSource?: unknown } } + const source = spec.header?.toolSchemasSource + if (source !== undefined && typeof source !== 'string') throw new Error(`${CATALOG_SCENARIO}/snapshot.yml: header.toolSchemasSource must be a string`) + const paths = [`${CATALOG_SCENARIO}/system-prompt.expected.md`, `${source === undefined ? CATALOG_SCENARIO : `snapshots/${source}`}/tool-schemas.expected.json`] + for (const path of paths) { + try { + git('cat-file', '-e', `${rev}:${path}`) + } catch (error) { + throw new Error(`catalog file ${path} is missing at ${rev}`, { cause: error }) + } + } + return paths +} + +function git(...args: string[]): string { + return execFileSync('git', args, { encoding: 'utf8', maxBuffer: 1 << 30 }) +} + +if (import.meta.main) { + const { values } = parseArgs({ options: { base: { type: 'string' }, head: { type: 'string' }, out: { type: 'string' } } }) + if (!values.base || !values.head || !values.out) throw new Error('usage: snapshot-diff-page.ts --base --head --out ') + const short = (rev: string) => git('rev-parse', '--short', rev).trim() + const files = parseUnifiedDiff(git('-c', 'core.quotePath=false', 'diff', '--no-color', '--no-renames', '--unified=5', values.base, values.head, '--', 'snapshots/')) + // A PR that moves the tool schema source shows both the old and the new file. + const catalog = [...new Set([...catalogPaths(values.base), ...catalogPaths(values.head)])] + const page = renderSnapshotDiffPage(groupDiffs(files, catalog), `${short(values.base)} → ${short(values.head)}`) + mkdirSync(dirname(values.out), { recursive: true }) + writeFileSync(values.out, page) +} From aa90f0be5679c97e03d3f86817b53eaf0a037c34 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:10:50 +0800 Subject: [PATCH 028/404] feat(subagent): attach SubagentError codes to delegation tool failures Delegation, discovery, and control tools threw plain Errors for missing caller context, invalid selections, depth limits, and corrupt or unavailable child state, so tool/result records carried no error.code. SubagentDepthError now extends SubagentError with DEPTH_EXCEEDED; new SubagentError codes cover disabled or disallowed preset and model selection, invalid depth and cwd, a missing working-directory service, a failed join of the parent preset revision, and structured output submitted with pending input. Missing callers and services use ToolContextUnavailableError, and hand-checked route fields use ToolArgsError. A corrupt cold-restore descriptor becomes NOT_RESUMABLE, and the schedule tools read the delegation depth inside their error mapping. Refs #7869 --- packages/schedule/tool-schedule/src/index.ts | 6 ++--- .../tool-schedule/tests/tool-schedule.spec.ts | 15 +++++++++++ .../tests/subagent-spawn-in-process.spec.ts | 5 +++- packages/subagent/subagent/README.i18n.yaml | 4 +-- packages/subagent/subagent/README.md | 2 +- packages/subagent/subagent/README.zh.md | 2 +- packages/subagent/subagent/src/child-agent.ts | 25 ++++++++++++----- packages/subagent/subagent/src/depth.ts | 5 ++-- packages/subagent/subagent/src/manager.ts | 15 +++++++++-- .../subagent/subagent/src/out-of-process.ts | 6 +++-- packages/subagent/subagent/src/structured.ts | 5 +++- .../subagent/tests/child-agent.spec.ts | 8 ++++-- .../tests/continuation-presets.spec.ts | 17 +++++++++++- .../subagent/tests/continuation.spec.ts | 27 ++++++++++++++++++- .../subagent/tests/out-of-process.spec.ts | 8 +++--- .../subagent/tests/structured.spec.ts | 2 ++ .../subagent/tests/working-directory.spec.ts | 6 ++++- .../tool-subagent-control/src/index.ts | 6 ++--- .../tool-subagent-control/src/list-agents.ts | 4 +-- .../tests/list-agents.spec.ts | 1 + .../tests/tool-subagent-control.spec.ts | 2 ++ .../subagent/tool-subagent/README.i18n.yaml | 4 +-- packages/subagent/tool-subagent/README.md | 2 +- packages/subagent/tool-subagent/README.zh.md | 2 +- packages/subagent/tool-subagent/src/index.ts | 12 ++++++--- .../subagent/tool-subagent/src/list-models.ts | 22 +++++++-------- .../tool-subagent/src/model-selection.ts | 20 +++++++++----- .../tool-subagent/src/preset-selection.ts | 9 +++++-- .../tool-subagent/tests/list-models.spec.ts | 20 ++++++++++---- .../tests/model-selection-settings.spec.ts | 1 + .../tests/model-selection.spec.ts | 16 ++++++++++- .../tests/preset-selection.spec.ts | 10 +++++-- .../tool-subagent/tests/tool-subagent.spec.ts | 2 ++ .../session.v4.jsonl | 2 +- .../session.2.v4.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- 36 files changed, 223 insertions(+), 74 deletions(-) diff --git a/packages/schedule/tool-schedule/src/index.ts b/packages/schedule/tool-schedule/src/index.ts index ab1ed612dc..65040e4c93 100644 --- a/packages/schedule/tool-schedule/src/index.ts +++ b/packages/schedule/tool-schedule/src/index.ts @@ -303,10 +303,10 @@ async function runForCaller( ): Promise | SubagentSessionError | InternalScheduleError> { const agent = exec.agent if (agent === undefined) return internalError() - if (delegationDepthOf(agent) > 0) { - return { code: 'subagent_session', message: 'A delegated subagent cannot use scheduled tasks.' } - } try { + if (delegationDepthOf(agent) > 0) { + return { code: 'subagent_session', message: 'A delegated subagent cannot use scheduled tasks.' } + } return await operation(agent) } catch (error: unknown) { if (error instanceof ScheduleInputError) { diff --git a/packages/schedule/tool-schedule/tests/tool-schedule.spec.ts b/packages/schedule/tool-schedule/tests/tool-schedule.spec.ts index 6d3d189d95..983f8a5daf 100644 --- a/packages/schedule/tool-schedule/tests/tool-schedule.spec.ts +++ b/packages/schedule/tool-schedule/tests/tool-schedule.spec.ts @@ -229,6 +229,21 @@ describe('Schedule model tools', () => { expect((await test.service.list({})).total).toBe(0) }) + it('answers internal_error when the caller carries an invalid runtime delegation depth', async () => { + const test = await harness(); tests.push(test) + const caller = { ...agentFor(test.ctx, 'invalid-depth'), options: { subagentDepth: -1 } } + await test.ctx.agents.register(caller) + await mountToolSchedule(test.ctx, caller) + for (const [name, args] of CALLS) { + const result = await executeToolFixture(test.ctx, { + callId: ToolCallId('invalid-depth-call'), signal: new AbortController().signal, name, arguments: args, agent: caller, + }) + expect(result.isError).toBe(false) + expect(result.value).toEqual(INTERNAL_ERROR) + } + expect((await test.service.list({})).total).toBe(0) + }) + it('describes the create parameters for the model', async () => { const test = await setup() const schema = test.ctx.tools.schemas(test.agent).find(candidate => candidate.name === 'schedule_create') diff --git a/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts b/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts index c254b67c8c..3ffd937d4d 100644 --- a/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts +++ b/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts @@ -131,7 +131,10 @@ describe('dsh-subagent-spawn-in-process', () => { const { ctx, parent } = await setup([]) // parent is depth 0, child would be depth 1 — cap at 0 forbids any child. await expect(start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent, maxDepth: 0 })) - .rejects.toThrow('subagent depth 1 exceeds maxDepth 0') + .rejects.toMatchObject({ + name: 'SubagentDepthError', code: 'DEPTH_EXCEEDED', message: 'subagent depth 1 exceeds maxDepth 0', + attemptedDepth: 1, maxDepth: 0, + }) }) it('maps a child that hit its token ceiling to stopReason "max-tokens"', async () => { diff --git a/packages/subagent/subagent/README.i18n.yaml b/packages/subagent/subagent/README.i18n.yaml index 4ff564cb25..ceaac3229a 100644 --- a/packages/subagent/subagent/README.i18n.yaml +++ b/packages/subagent/subagent/README.i18n.yaml @@ -39,8 +39,8 @@ en: bf3175c2218a16dd zh: 4be9271efe71ddb7 /deepseek-ai-dsh-subagent/use-this-package/failure-and-recovery: - en: 0dc416ded19e304e - zh: 4726e5fe5f188709 + en: f5393c65bf8ee460 + zh: d037d42bc967f17b /deepseek-ai-dsh-subagent/understand-the-implementation: en: 74d91b364b23f88d zh: 19cc558105efe8df diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index b8fd869989..dcad891799 100644 --- a/packages/subagent/subagent/README.md +++ b/packages/subagent/subagent/README.md @@ -79,7 +79,7 @@ In-process spawn accepts an independent `agentPreset`; fork and external backend ### Failure and recovery -Starting without the `agents` service rejects with `CONTINUATION_UNAVAILABLE`; an available runtime rejects a missing or replaced parent with `UNAUTHORIZED`. Providers implementing neither execution method are rejected at registration with `UNSUPPORTED_CAPABILITY`; unsupported requested capabilities reject creation with the same code. If a provider is removed or replaced while directory resolution is pending, creation rejects with `PROVIDER_CHANGED` before invoking either provider; retry the delegation against the current registration. The caller signal cancels only unpublished work; after publication, `dispose()` cancels the exact activation and waits for its resource cleanup. Creation descendants continue independently; hosts must await `drainDescendants([root])` before disposing the root handle to stop all members and await pending startup. `result` settles after teardown and notifications, carrying output, optional structured data, and a stop reason; capture failures reject it after teardown. Cleanup failures reject `dispose()` and mark the lifecycle end as failed; the result promise and parent notification retain the captured execution result. +Starting without the `agents` service rejects with `CONTINUATION_UNAVAILABLE`; an available runtime rejects a missing or replaced parent with `UNAUTHORIZED`. Providers implementing neither execution method are rejected at registration with `UNSUPPORTED_CAPABILITY`; unsupported requested capabilities reject creation with the same code. If a provider is removed or replaced while directory resolution is pending, creation rejects with `PROVIDER_CHANGED` before invoking either provider; retry the delegation against the current registration. Every creation failure below is a `SubagentError`: a child beyond the requested depth rejects with the `SubagentDepthError` subclass and `DEPTH_EXCEEDED`, an invalid runtime `subagentDepth` with `INVALID_DEPTH`, a child that cannot join its creator's preset revision with `PRESET_UNAVAILABLE`, a local child without the working-directory service with `WORKING_DIRECTORY_UNAVAILABLE`, and an out-of-process child whose cwd is relative or not enterable with `INVALID_CWD`. A cold target whose persisted descriptor is corrupt rejects with `NOT_RESUMABLE`, and `structured_output` called while input is pending fails with `STRUCTURED_OUTPUT_PENDING_INPUT`. The caller signal cancels only unpublished work; after publication, `dispose()` cancels the exact activation and waits for its resource cleanup. Creation descendants continue independently; hosts must await `drainDescendants([root])` before disposing the root handle to stop all members and await pending startup. `result` settles after teardown and notifications, carrying output, optional structured data, and a stop reason; capture failures reject it after teardown. Cleanup failures reject `dispose()` and mark the lifecycle end as failed; the result promise and parent notification retain the captured execution result. ----- diff --git a/packages/subagent/subagent/README.zh.md b/packages/subagent/subagent/README.zh.md index e0f8f35bda..dfe7d1f835 100644 --- a/packages/subagent/subagent/README.zh.md +++ b/packages/subagent/subagent/README.zh.md @@ -79,7 +79,7 @@ kind: "package-reference" ### 失败与恢复 -缺少 `agents` 服务时,启动请求以 `CONTINUATION_UNAVAILABLE` 拒绝;运行时可用但父级缺失或被替换时,以 `UNAUTHORIZED` 拒绝。未实现任何执行方法的提供方会在注册时以 `UNSUPPORTED_CAPABILITY` 被拒绝;请求不受支持的能力会以同一码使创建失败。如果等待目录解析期间提供方被移除或替换,创建会在调用任何一方之前以 `PROVIDER_CHANGED` 拒绝;调用方可根据当前注册重试委派。调用方信号仅取消尚未发布的工作;发布后通过 `dispose()` 取消该次 activation,并等待其资源清理完成。创建后代独立继续运行;宿主必须在释放根句柄前等待 `drainDescendants([root])`,以停止所有成员并等待正在启动的工作。`result` 在清理与通知结束后完成,携带输出、可选结构化数据与停止原因;结果捕获故障在清理后使其拒绝。清理失败使 `dispose()` 拒绝,并将生命周期结束事件标记为失败;结果 promise 与父级通知保留已捕获的执行结果。 +缺少 `agents` 服务时,启动请求以 `CONTINUATION_UNAVAILABLE` 拒绝;运行时可用但父级缺失或被替换时,以 `UNAUTHORIZED` 拒绝。未实现任何执行方法的提供方会在注册时以 `UNSUPPORTED_CAPABILITY` 被拒绝;请求不受支持的能力会以同一码使创建失败。如果等待目录解析期间提供方被移除或替换,创建会在调用任何一方之前以 `PROVIDER_CHANGED` 拒绝;调用方可根据当前注册重试委派。以下创建失败均为 `SubagentError`:超出请求深度的子代以 `SubagentDepthError` 子类和 `DEPTH_EXCEEDED` 拒绝,无效的运行时 `subagentDepth` 以 `INVALID_DEPTH` 拒绝,无法加入创建者 preset 版本的子代以 `PRESET_UNAVAILABLE` 拒绝,缺少工作目录服务的本地子代以 `WORKING_DIRECTORY_UNAVAILABLE` 拒绝,cwd 为相对路径或不可进入的进程外子代以 `INVALID_CWD` 拒绝。持久化 descriptor 损坏的冷目标以 `NOT_RESUMABLE` 拒绝,有待处理输入时调用 `structured_output` 以 `STRUCTURED_OUTPUT_PENDING_INPUT` 失败。调用方信号仅取消尚未发布的工作;发布后通过 `dispose()` 取消该次 activation,并等待其资源清理完成。创建后代独立继续运行;宿主必须在释放根句柄前等待 `drainDescendants([root])`,以停止所有成员并等待正在启动的工作。`result` 在清理与通知结束后完成,携带输出、可选结构化数据与停止原因;结果捕获故障在清理后使其拒绝。清理失败使 `dispose()` 拒绝,并将生命周期结束事件标记为失败;结果 promise 与父级通知保留已捕获的执行结果。 ----- diff --git a/packages/subagent/subagent/src/child-agent.ts b/packages/subagent/subagent/src/child-agent.ts index 98ebfc9d5d..9f4626641c 100644 --- a/packages/subagent/subagent/src/child-agent.ts +++ b/packages/subagent/subagent/src/child-agent.ts @@ -28,10 +28,10 @@ import type {} from '@deepseek-ai/dsh-agent-preset-registry' import { delegationDepthOf } from './depth.ts' import { SubagentError } from './error.ts' -/** Thrown when starting a child would exceed the requested depth cap. */ -export class SubagentDepthError extends Error { +/** Thrown when starting a child would exceed the requested depth cap; `code` is `DEPTH_EXCEEDED`. */ +export class SubagentDepthError extends SubagentError { constructor(public readonly attemptedDepth: number, public readonly maxDepth: number) { - super(`subagent depth ${attemptedDepth} exceeds maxDepth ${maxDepth}`) + super(`subagent depth ${attemptedDepth} exceeds maxDepth ${maxDepth}`, 'DEPTH_EXCEEDED') this.name = 'SubagentDepthError' } } @@ -44,12 +44,12 @@ export class SubagentDepthError extends Error { * @param maxDepth - optional absolute cap the resolved depth must not exceed. * @returns the child's non-negative safe-integer depth. * @throws {SubagentDepthError} when the resolved depth exceeds `maxDepth`. - * @throws {RangeError} when the resolved depth leaves the safe-integer range. + * @throws {SubagentError} `DEPTH_EXCEEDED` when the resolved depth leaves the safe-integer range. */ export function resolveChildDepth(parent: Agent, maxDepth: number | undefined): number { const childDepth = delegationDepthOf(parent) + 1 if (!Number.isSafeInteger(childDepth)) { - throw new RangeError('subagent child depth exceeds the safe-integer range') + throw new SubagentError('subagent child depth exceeds the safe-integer range', 'DEPTH_EXCEEDED') } if (maxDepth !== undefined && childDepth > maxDepth) { throw new SubagentDepthError(childDepth, maxDepth) @@ -183,6 +183,8 @@ export const SUBAGENT_DELEGATION_CONTEXT * @param parent - creator for fresh delegation; absent during target-only restoration. * @param composition - independent preset and any overrides read from a historical descriptor. * @returns A promise when mounting an independent preset; otherwise completes synchronously. + * @throws {SubagentError} `PRESET_UNAVAILABLE` when the preset service is absent or the + * child cannot join its creator's preset revision. */ export function applyChildComposition( childCtx: Context, @@ -198,7 +200,18 @@ export function applyChildComposition( applyChildOverrides(childCtx, composition) }) } - if (parent !== undefined) childCtx.get('agentPresets')?.composeFrom(childCtx, parent.ctx) + if (parent !== undefined) { + try { + childCtx.get('agentPresets')?.composeFrom(childCtx, parent.ctx) + } catch (error: unknown) { + // The registry cannot import this package, so its plain join failures are classified here. + throw new SubagentError( + 'the child cannot join the parent agent\'s current preset revision', + 'PRESET_UNAVAILABLE', + { cause: error }, + ) + } + } applyChildOverrides(childCtx, composition) } diff --git a/packages/subagent/subagent/src/depth.ts b/packages/subagent/subagent/src/depth.ts index d9fabab860..033e953bf5 100644 --- a/packages/subagent/subagent/src/depth.ts +++ b/packages/subagent/subagent/src/depth.ts @@ -7,6 +7,7 @@ */ import type { Agent } from '@deepseek-ai/dsh-agent' +import { SubagentError } from './error.ts' declare module '@deepseek-ai/dsh-agent' { interface AgentOptions { @@ -23,12 +24,12 @@ declare module '@deepseek-ai/dsh-agent' { * let it delegate as if it were top-level. * @param agent - the agent whose header and options carry the depth. * @returns its non-negative safe-integer depth. - * @throws if the runtime `AgentOptions.subagentDepth` is not a non-negative safe integer. + * @throws {SubagentError} `INVALID_DEPTH` if the runtime `AgentOptions.subagentDepth` is not a non-negative safe integer. */ export function delegationDepthOf(agent: Agent): number { const runtime = agent.options.subagentDepth if (runtime !== undefined && (!Number.isSafeInteger(runtime) || runtime < 0 || Object.is(runtime, -0))) { - throw new TypeError('agent subagentDepth must be a non-negative safe integer') + throw new SubagentError('agent subagentDepth must be a non-negative safe integer', 'INVALID_DEPTH') } // The header value was validated at the session boundary (creation and // persistence load both construct through the store). diff --git a/packages/subagent/subagent/src/manager.ts b/packages/subagent/subagent/src/manager.ts index db6f04b019..fa97141c76 100644 --- a/packages/subagent/subagent/src/manager.ts +++ b/packages/subagent/subagent/src/manager.ts @@ -830,7 +830,9 @@ export class SubagentManager { child.session.append('subagent/descriptor', create.descriptor) appendDelegatedPolicyOverrides(child.session, create.delegatedPolicies) const workingDirectory = childCtx.get('workingDirectory') - if (workingDirectory === undefined) throw new Error('local subagents require the working-directory service') + if (workingDirectory === undefined) { + throw new SubagentError('local subagents require the working-directory service', 'WORKING_DIRECTORY_UNAVAILABLE') + } await workingDirectory.set(child, create.cwd, inputs.signal) } if (inputs.composition.agentPreset === undefined) await applyChildComposition(childCtx, create?.parent, inputs.composition) @@ -1205,7 +1207,16 @@ export class SubagentManager { using source = await this.observeContinuation(childId, signal) this.assertAdmitting(root) const ownEvents = source.events.slice(source.inheritedEventCount) - const descriptor = foldSubagentDescriptor(ownEvents) + let descriptor: ReturnType + try { + descriptor = foldSubagentDescriptor(ownEvents) + } catch (error: unknown) { + throw new SubagentError( + `subagent "${childId}" has a corrupt continuation descriptor and cannot be resumed; choose a different target`, + 'NOT_RESUMABLE', + { cause: error }, + ) + } if (descriptor === undefined || descriptor.mode !== 'continuable') { throw new SubagentError( `subagent "${childId}" has no supported continuation state and cannot be resumed; choose a different target`, diff --git a/packages/subagent/subagent/src/out-of-process.ts b/packages/subagent/subagent/src/out-of-process.ts index d8a5519c96..84f46ae387 100644 --- a/packages/subagent/subagent/src/out-of-process.ts +++ b/packages/subagent/subagent/src/out-of-process.ts @@ -13,6 +13,7 @@ import { accessSync, constants, statSync } from 'node:fs' import { isAbsolute } from 'node:path' import type { ContentBlock } from '@deepseek-ai/dsh-llm' +import { SubagentError } from './error.ts' import type { SubagentCapabilities, SubagentResult, SubagentRun, SubagentStopReason } from './types.ts' /** Maximum UTF-8 size of {@link SubagentResult.diagnostic}. */ @@ -100,13 +101,14 @@ function isEnterableDirectory(path: string): boolean { * @param label - which source supplied the value, for the diagnostic. * @param cwd - the candidate working directory. * @returns `cwd`, validated. + * @throws {SubagentError} `INVALID_CWD` when `cwd` is relative or not an enterable directory. */ export function assertUsableCwd(prefix: string, label: string, cwd: string): string { if (!isAbsolute(cwd)) { - throw new Error(`${prefix}: ${label} must be an absolute path: ${cwd}`) + throw new SubagentError(`${prefix}: ${label} must be an absolute path: ${cwd}`, 'INVALID_CWD') } if (!isEnterableDirectory(cwd)) { - throw new Error(`${prefix}: ${label} is not an accessible directory: ${cwd}`) + throw new SubagentError(`${prefix}: ${label} is not an accessible directory: ${cwd}`, 'INVALID_CWD') } return cwd } diff --git a/packages/subagent/subagent/src/structured.ts b/packages/subagent/subagent/src/structured.ts index eeb8c1e86b..81f0952d09 100644 --- a/packages/subagent/subagent/src/structured.ts +++ b/packages/subagent/subagent/src/structured.ts @@ -14,6 +14,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { ToolSchema } from '@deepseek-ai/dsh-llm' import type { ToolExecution, ToolRunContext } from '@deepseek-ai/dsh-tools' import { ToolArgsError, validateJsonSchemaValue, type ObjectJsonSchema } from '@deepseek-ai/dsh-tools' +import { SubagentError } from './error.ts' /** The model-facing tool name a structured child must call to finish. */ export const STRUCTURED_OUTPUT_TOOL = 'structured_output' @@ -96,7 +97,9 @@ export function attachStructuredRuntime( // ToolArgsError → isError result with INVALID_ARGS: the model retries // within the same turn, exactly like a schema-validated defineTool call. if (violations.length > 0) throw new ToolArgsError(violations) - if (!canComplete()) throw new Error('Process pending messages before submitting structured output.') + if (!canComplete()) { + throw new SubagentError('Process pending messages before submitting structured output.', 'STRUCTURED_OUTPUT_PENDING_INPUT') + } // Two-phase commit, keyed by THIS execution: later transformable // waterfalls may still turn the success into an error. ToolRuntime has // already frozen model-bound arguments at the actual input boundary. diff --git a/packages/subagent/subagent/tests/child-agent.spec.ts b/packages/subagent/subagent/tests/child-agent.spec.ts index 0b661cd21d..ad47b8f6d4 100644 --- a/packages/subagent/subagent/tests/child-agent.spec.ts +++ b/packages/subagent/subagent/tests/child-agent.spec.ts @@ -92,12 +92,16 @@ describe('delegation depth limits', () => { it.each([-1, -0, 0.5, Number.NaN, Number.POSITIVE_INFINITY])('rejects an invalid runtime depth %s', (depth) => { const parent = parentAgent() parent.options.subagentDepth = depth - expect(() => resolveChildDepth(parent, undefined)).toThrow('agent subagentDepth must be a non-negative safe integer') + expect(() => resolveChildDepth(parent, undefined)).toThrow(expect.objectContaining({ + name: 'SubagentError', code: 'INVALID_DEPTH', message: 'agent subagentDepth must be a non-negative safe integer', + })) }) it('rejects a child depth beyond the exact integer range', () => { const parent = parentAgent() parent.options.subagentDepth = Number.MAX_SAFE_INTEGER - expect(() => resolveChildDepth(parent, undefined)).toThrow('subagent child depth exceeds the safe-integer range') + expect(() => resolveChildDepth(parent, undefined)).toThrow(expect.objectContaining({ + name: 'SubagentError', code: 'DEPTH_EXCEEDED', message: 'subagent child depth exceeds the safe-integer range', + })) }) }) diff --git a/packages/subagent/subagent/tests/continuation-presets.spec.ts b/packages/subagent/subagent/tests/continuation-presets.spec.ts index 941d7faf16..594be164ac 100644 --- a/packages/subagent/subagent/tests/continuation-presets.spec.ts +++ b/packages/subagent/subagent/tests/continuation-presets.spec.ts @@ -1,7 +1,7 @@ /** Independent spawn presets and compatibility of persisted child compositions. */ import { mountWorkingDirectoryFixture } from './working-directory-fixture.ts' -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' @@ -124,6 +124,21 @@ describe('child preset start validation', () => { expect(adapter.requests).toEqual([]) }) + it('classifies a failed join of the parent preset revision as PRESET_UNAVAILABLE', async () => { + const { ctx, parent, adapter } = await setup() + const failure = new Error('Parent preset revision is unavailable') + vi.spyOn(ctx.agentPresets, 'composeFrom').mockImplementation(() => { throw failure }) + + await expect(ctx.subagents.startActivation(startSpec(parent))).rejects.toMatchObject({ + name: 'SubagentError', + code: 'PRESET_UNAVAILABLE', + message: 'the child cannot join the parent agent\'s current preset revision', + cause: failure, + }) + expect(ctx.agents.list().map(agent => agent.id)).toEqual([parent.id]) + expect(adapter.requests).toEqual([]) + }) + it('rolls back an independent spawn when the preset service has unloaded', async () => { const { ctx, parent, adapter, presets } = await setup() await presets.dispose() diff --git a/packages/subagent/subagent/tests/continuation.spec.ts b/packages/subagent/subagent/tests/continuation.spec.ts index a3cb8d3b93..3948cde2f0 100644 --- a/packages/subagent/subagent/tests/continuation.spec.ts +++ b/packages/subagent/subagent/tests/continuation.spec.ts @@ -766,7 +766,7 @@ describe('SubagentRuntime.startActivation', () => { delivery: 'parent', ...startSpec(parent), prompt: message('deep'), parent, maxDepth: 0, - })).rejects.toThrow(/exceeds maxDepth 0/) + })).rejects.toMatchObject({ name: 'SubagentDepthError', code: 'DEPTH_EXCEEDED', message: expect.stringMatching(/exceeds maxDepth 0/) as string }) expect(ctx.agents.list().map(agent => agent.id)).toEqual([SessionId('parent')]) }) @@ -1160,6 +1160,31 @@ describe('target-only Queue residency routing', () => { .rejects.toMatchObject({ code: 'NOT_RESUMABLE' }) }) + it('rejects a cold target whose persisted descriptor is corrupt as not resumable', async () => { + const { ctx, parent } = await setup([]) + const childId = SessionId('child-with-corrupt-descriptor') + const child = await ctx.agents.create({ + sessionId: childId, + meta: { origin: 'subagent', parentSession: parent.id }, + agentOptions: { provider: 'mock', model: 'mock' }, + setup: (_childCtx, agent) => { + agent.session.append('subagent/descriptor', { + version: SUBAGENT_DESCRIPTOR_VERSION, mode: 'continuable', provider: 'spawn', label: 7, + } as never) + }, + }) + await ctx.sessions.flush(child.agent.session) + await child.dispose() + + await expect(ctx.subagents.sendMessage(parent, childId, message('continue'), { signal: testSignal })) + .rejects.toMatchObject({ + name: 'SubagentError', + code: 'NOT_RESUMABLE', + message: `subagent "${childId}" has a corrupt continuation descriptor and cannot be resumed; choose a different target`, + cause: expect.objectContaining({ message: 'persisted subagent descriptor label must be a string' }) as Error, + }) + }) + it('reports an unknown child id as unavailable', async () => { const { ctx } = await setup([]) await expect(queuePrompt(ctx, SessionId('missing'), message('hello'))) diff --git a/packages/subagent/subagent/tests/out-of-process.spec.ts b/packages/subagent/subagent/tests/out-of-process.spec.ts index f4db734e96..79c44ccf4b 100644 --- a/packages/subagent/subagent/tests/out-of-process.spec.ts +++ b/packages/subagent/subagent/tests/out-of-process.spec.ts @@ -42,8 +42,8 @@ describe('assertPositiveFinite', () => { describe('child cwd resolution', () => { it('accepts an absolute enterable directory and rejects relative or missing paths', () => { expect(assertUsableCwd('p', 'config cwd', tmpdir())).toBe(tmpdir()) - expect(() => assertUsableCwd('p', 'config cwd', 'relative/path')).toThrow('must be an absolute path') - expect(() => assertUsableCwd('p', 'config cwd', join(tmpdir(), 'dsh-no-such-dir-xyz'))).toThrow('not an accessible directory') + expect(() => assertUsableCwd('p', 'config cwd', 'relative/path')).toThrow(expect.objectContaining({ name: 'SubagentError', code: 'INVALID_CWD', message: expect.stringContaining('must be an absolute path') as string })) + expect(() => assertUsableCwd('p', 'config cwd', join(tmpdir(), 'dsh-no-such-dir-xyz'))).toThrow(expect.objectContaining({ name: 'SubagentError', code: 'INVALID_CWD', message: expect.stringContaining('not an accessible directory') as string })) }) it('rejects an existing path that is a file, not a directory', () => { @@ -51,7 +51,7 @@ describe('child cwd resolution', () => { const file = join(tmp, 'plain.txt') try { writeFileSync(file, 'not a dir\n') - expect(() => assertUsableCwd('p', 'config cwd', file)).toThrow('not an accessible directory') + expect(() => assertUsableCwd('p', 'config cwd', file)).toThrow(expect.objectContaining({ name: 'SubagentError', code: 'INVALID_CWD', message: expect.stringContaining('not an accessible directory') as string })) } finally { rmSync(tmp, { recursive: true, force: true }) } @@ -64,7 +64,7 @@ describe('child cwd resolution', () => { const tmp = mkdtempSync(join(tmpdir(), 'oop-noexec-')) chmodSync(tmp, 0o600) try { - expect(() => assertUsableCwd('p', 'config cwd', tmp)).toThrow('not an accessible directory') + expect(() => assertUsableCwd('p', 'config cwd', tmp)).toThrow(expect.objectContaining({ name: 'SubagentError', code: 'INVALID_CWD', message: expect.stringContaining('not an accessible directory') as string })) } finally { chmodSync(tmp, 0o700) rmSync(tmp, { recursive: true, force: true }) diff --git a/packages/subagent/subagent/tests/structured.spec.ts b/packages/subagent/subagent/tests/structured.spec.ts index 60f5f8b19e..ea0f4e5109 100644 --- a/packages/subagent/subagent/tests/structured.spec.ts +++ b/packages/subagent/subagent/tests/structured.spec.ts @@ -138,6 +138,8 @@ describe('in-process structured output', () => { const events = run.localAgent.session.snapshotEvents() const first = events.find(event => event.type === 'tool/result' && event.data.message.toolCallId === 'before-input') expect(first?.type === 'tool/result' && first.data.message.isError).toBe(true) + expect(first?.type === 'tool/result' && first.data.error) + .toEqual({ name: 'SubagentError', code: 'STRUCTURED_OUTPUT_PENDING_INPUT' }) expect(events.some(event => event.type === 'user/message' && event.data.id === messageId)).toBe(true) expect(JSON.stringify(adapter.requests.at(-1)?.messages)).toContain('Correction: submit answer 42 instead.') } finally { diff --git a/packages/subagent/subagent/tests/working-directory.spec.ts b/packages/subagent/subagent/tests/working-directory.spec.ts index f3cb6aa47d..befe01a1da 100644 --- a/packages/subagent/subagent/tests/working-directory.spec.ts +++ b/packages/subagent/subagent/tests/working-directory.spec.ts @@ -101,7 +101,11 @@ describe('subagent working directories', () => { provider: 'spawn', label: 'unavailable directory service', childId, parent, cwd: second, prompt: [{ type: 'text', text: 'child' }], signal: new AbortController().signal, - })).rejects.toThrow(/subagents require the working-directory service/) + })).rejects.toMatchObject({ + name: 'SubagentError', + code: 'WORKING_DIRECTORY_UNAVAILABLE', + message: expect.stringMatching(/subagents require the working-directory service/) as string, + }) expect(ctx.agents.list().map(agent => agent.id)).toEqual([parent.id]) expect(parent.session.snapshotEvents().filter(event => event.type === 'subagent/catalog')).toEqual([]) diff --git a/packages/subagent/tool-subagent-control/src/index.ts b/packages/subagent/tool-subagent-control/src/index.ts index b6b89603ac..8f9ecc95ba 100644 --- a/packages/subagent/tool-subagent-control/src/index.ts +++ b/packages/subagent/tool-subagent-control/src/index.ts @@ -10,7 +10,7 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import { ROOT_AGENT_NAME } from '@deepseek-ai/dsh-subagent' import type {} from '@deepseek-ai/dsh-system-prompt' @@ -73,7 +73,7 @@ export function apply(ctx: Context, config: Config = {}): void { async execute(args, exec) { const sender = exec.agent if (!sender) { - throw new Error('send_message requires a calling agent (exec.agent was undefined)') + throw new ToolContextUnavailableError('send_message requires a calling agent (exec.agent was undefined)') } const message: ContentBlock[] = [{ type: 'text', text: args.message }] const targetId = await ctx.subagents.resolveName(sender, args.agent, exec.signal) @@ -146,7 +146,7 @@ export function apply(ctx: Context, config: Config = {}): void { const caller = exec.agent if (!caller) { // Ancestor authority requires an exact live calling agent. - throw new Error('interrupt_agent requires a calling agent (exec.agent was undefined)') + throw new ToolContextUnavailableError('interrupt_agent requires a calling agent (exec.agent was undefined)') } const targetId = await ctx.subagents.resolveName(caller, args.agent, exec.signal) // The service authorizes the exact live caller against the target's diff --git a/packages/subagent/tool-subagent-control/src/list-agents.ts b/packages/subagent/tool-subagent-control/src/list-agents.ts index 50780cf91d..555b16181e 100644 --- a/packages/subagent/tool-subagent-control/src/list-agents.ts +++ b/packages/subagent/tool-subagent-control/src/list-agents.ts @@ -1,7 +1,7 @@ /** Discover the caller's entire subagent tree; the control plugin owns registration. */ import type { Context } from '@deepseek-ai/cordis' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { ToolDefinition } from '@deepseek-ai/dsh-tools' import type { Agent } from '@deepseek-ai/dsh-agent' import type { SessionId } from '@deepseek-ai/dsh-session' @@ -78,7 +78,7 @@ export function registerListAgents(ctx: Context): ToolDefinition { const parent = exec.agent if (!parent) { // Non-agent callers have no session whose children could be listed. - throw new Error('list_agents requires a calling agent (exec.agent was undefined)') + throw new ToolContextUnavailableError('list_agents requires a calling agent (exec.agent was undefined)') } const root = ctx.subagents.rootOf(parent) const entries = await ctx.subagents.listDescendants(root.id, exec.signal) diff --git a/packages/subagent/tool-subagent-control/tests/list-agents.spec.ts b/packages/subagent/tool-subagent-control/tests/list-agents.spec.ts index a1d0adf382..c927784c70 100644 --- a/packages/subagent/tool-subagent-control/tests/list-agents.spec.ts +++ b/packages/subagent/tool-subagent-control/tests/list-agents.spec.ts @@ -271,6 +271,7 @@ describe('list_agents', () => { const result = await callTool(ctx, 'list_agents', {}) expect(result.isError).toBe(true) expect(text(result)).toContain('requires a calling agent') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it('unregisters with its plugin fiber (HMR safety)', async () => { diff --git a/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts b/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts index 5ea4866a1c..c12f685212 100644 --- a/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts +++ b/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts @@ -463,6 +463,7 @@ describe('dsh-tool-subagent-control', () => { const result = await callTool(ctx, 'send_message', { agent: 'x', message: 'y' }) expect(result.isError).toBe(true) expect(text(result)).toContain('requires a calling agent') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it.each([{}, { interrupt: true }, { interrupt: false }])('unregisters and reloads with config %j (HMR safety)', async (config) => { @@ -692,5 +693,6 @@ describe('dsh-tool-subagent-control interrupt_agent', () => { const result = await callTool(ctx, 'interrupt_agent', { agent: 'x' }) expect(result.isError).toBe(true) expect(text(result)).toContain('requires a calling agent') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) }) diff --git a/packages/subagent/tool-subagent/README.i18n.yaml b/packages/subagent/tool-subagent/README.i18n.yaml index 35252c76ab..eb73b24381 100644 --- a/packages/subagent/tool-subagent/README.i18n.yaml +++ b/packages/subagent/tool-subagent/README.i18n.yaml @@ -36,8 +36,8 @@ en: 373abf7c7aa3e4f1 zh: be0b4d4a7371d360 /deepseek-ai-dsh-tool-subagent/understand-the-implementation/activation-ownership: - en: ef692c4d17290920 - zh: b1d0d3dab011e2cd + en: a72ddd82ad7810a1 + zh: 738f8fb157e51c59 /deepseek-ai-dsh-tool-subagent/understand-the-implementation/result-acknowledgement: en: 3c2d70d479be8e38 zh: 9aebdb72223a086e diff --git a/packages/subagent/tool-subagent/README.md b/packages/subagent/tool-subagent/README.md index e41c2161b6..f4d29d8b26 100644 --- a/packages/subagent/tool-subagent/README.md +++ b/packages/subagent/tool-subagent/README.md @@ -94,7 +94,7 @@ One instance is one provider plus one tool name. The plugin registers its defini ### Activation ownership -The tool calls `ctx.subagents.startActivation()` with parent delivery selected. The runtime owns startup cancellation, execution, outcome reporting, and cleanup. A startup failure is an errored tool result; failures after publication arrive through the completion notice, with diagnostics and partial output preserved by the runtime. +The tool calls `ctx.subagents.startActivation()` with parent delivery selected. The runtime owns startup cancellation, execution, outcome reporting, and cleanup. A startup failure is an errored tool result. Rejections before startup are coded: a missing calling Agent, `llm` service, or effective parent route throws `ToolContextUnavailableError`; an empty or unpaired route field throws `ToolArgsError`; and `SubagentError` reports a disabled selection (`MODEL_SELECTION_DISABLED`, `PRESET_SELECTION_DISABLED`), a preset outside the allowlist (`PRESET_NOT_ALLOWED`), an unauthorized route (`UNAUTHORIZED`), an unregistered discovery provider (`NO_PROVIDER`), or a provider replaced during route preflight (`PROVIDER_CHANGED`). Failures after publication arrive through the completion notice, with diagnostics and partial output preserved by the runtime. ### Result acknowledgement diff --git a/packages/subagent/tool-subagent/README.zh.md b/packages/subagent/tool-subagent/README.zh.md index 2093ff093a..5760c7f02c 100644 --- a/packages/subagent/tool-subagent/README.zh.md +++ b/packages/subagent/tool-subagent/README.zh.md @@ -94,7 +94,7 @@ kind: "package-reference" ### Activation 所有权 -工具调用 `ctx.subagents.startActivation()`,并选择向父任务交付。运行时拥有启动取消、执行、结果汇报与清理。启动失败产生出错的工具结果;发布后的失败通过完成通知到达,运行时保留诊断和部分输出。 +工具调用 `ctx.subagents.startActivation()`,并选择向父任务交付。运行时拥有启动取消、执行、结果汇报与清理。启动失败产生出错的工具结果。启动前的拒绝都带 code:缺少调用方 Agent、`llm` 服务或有效的父级路由时抛出 `ToolContextUnavailableError`;路由字段为空或未成对提供时抛出 `ToolArgsError`;`SubagentError` 报告选择被禁用(`MODEL_SELECTION_DISABLED`、`PRESET_SELECTION_DISABLED`)、preset 不在允许列表中(`PRESET_NOT_ALLOWED`)、路由未授权(`UNAUTHORIZED`)、发现查询的提供方未注册(`NO_PROVIDER`),或路由预检期间提供方被替换(`PROVIDER_CHANGED`)。发布后的失败通过完成通知到达,运行时保留诊断和部分输出。 ### 结果确认 diff --git a/packages/subagent/tool-subagent/src/index.ts b/packages/subagent/tool-subagent/src/index.ts index 5f2f089363..4cce53ec87 100644 --- a/packages/subagent/tool-subagent/src/index.ts +++ b/packages/subagent/tool-subagent/src/index.ts @@ -9,7 +9,7 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-agent-preset-registry' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { ToolDefinition } from '@deepseek-ai/dsh-tools' import type { AgentOptions } from '@deepseek-ai/dsh-agent' import { ReasoningEffortId } from '@deepseek-ai/dsh-llm' @@ -18,6 +18,7 @@ import { assertSubagentMaxDepth, delegationDepthOf, parentAgentOptionsForDelegation, + SubagentError, } from '@deepseek-ai/dsh-subagent' import type { SubagentProvider } from '@deepseek-ai/dsh-subagent' import { @@ -275,7 +276,7 @@ export async function apply(ctx: Context, config: Config): Promise { const parent = exec.agent if (!parent) { // Non-agent callers provide no parent for delegation ownership. - throw new Error('subagent tool requires a calling agent (exec.agent was undefined)') + throw new ToolContextUnavailableError('subagent tool requires a calling agent (exec.agent was undefined)') } const routes = subagentModelSelectionPolicy(subagentModelSelectionProjectionHandle, parent.session) @@ -298,7 +299,7 @@ export async function apply(ctx: Context, config: Config): Promise { if (requiresRoutePreflight) { const llm = ctx.get('llm') if (llm === undefined) { - throw new Error('cannot resolve the selected child LLM route because the `llm` service is unavailable') + throw new ToolContextUnavailableError('cannot resolve the selected child LLM route because the `llm` service is unavailable') } const inheritParentReasoningEffort = providerRouteDefaults === undefined && !hasDelegationModelRequest(modelRequest) await preflightChildLlmRoute( @@ -309,7 +310,10 @@ export async function apply(ctx: Context, config: Config): Promise { inheritParentReasoningEffort, ) if (ctx.subagents.getProvider(config.provider) !== subagentProvider) { - throw new Error(`subagent provider "${config.provider}" changed while resolving the child LLM route; retry the delegation`) + throw new SubagentError( + `subagent provider "${config.provider}" changed while resolving the child LLM route; retry the delegation`, + 'PROVIDER_CHANGED', + ) } } exec.signal.throwIfAborted() diff --git a/packages/subagent/tool-subagent/src/list-models.ts b/packages/subagent/tool-subagent/src/list-models.ts index 966680a669..4c0ae9b94e 100644 --- a/packages/subagent/tool-subagent/src/list-models.ts +++ b/packages/subagent/tool-subagent/src/list-models.ts @@ -3,8 +3,8 @@ import type { Context } from '@deepseek-ai/cordis' import type LlmRuntime from '@deepseek-ai/dsh-llm' import type { LlmProviderInfo } from '@deepseek-ai/dsh-llm' -import { defineTool } from '@deepseek-ai/dsh-tools' -import { parentAgentOptionsForDelegation } from '@deepseek-ai/dsh-subagent' +import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' +import { parentAgentOptionsForDelegation, SubagentError } from '@deepseek-ai/dsh-subagent' import type { ToolRunContext } from '@deepseek-ai/dsh-tools' import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection' import type { AllowedModelRoute, ModelSelectionPolicy } from './model-selection.ts' @@ -28,7 +28,7 @@ function registeredProvider( .filter(candidate => policy.routes.some(route => route.provider === candidate.id)) .map(candidate => candidate.id) .join(', ') || '(none)' - throw new Error(`LLM provider "${providerId}" is not registered; available providers: ${available}`) + throw new SubagentError(`LLM provider "${providerId}" is not registered; available providers: ${available}`, 'NO_PROVIDER') } /** Render one advertised or resolved model. */ @@ -43,24 +43,24 @@ async function listSubagentModels( request: ListSubagentModelsRequest, exec: ToolRunContext, ): Promise { - if (exec.agent === undefined) throw new Error('list_subagent_models requires a calling agent') + if (exec.agent === undefined) throw new ToolContextUnavailableError('list_subagent_models requires a calling agent') const routes = subagentModelSelectionPolicy(policyHandle, exec.agent.session) let policy = routes === undefined ? undefined : { routes } const selectionEnabled = policy !== undefined if (policy === undefined) { const { provider, model } = parentAgentOptionsForDelegation(exec.agent) if (provider === undefined || model === undefined) { - throw new Error('cannot discover child LLM routes without a parent provider and model') + throw new ToolContextUnavailableError('cannot discover child LLM routes without a parent provider and model') } policy = { routes: [{ provider, model }] } } const { signal } = exec const llm = ctx.get('llm') if (llm === undefined) { - throw new Error('cannot discover child LLM routes because the `llm` service is unavailable') + throw new ToolContextUnavailableError('cannot discover child LLM routes because the `llm` service is unavailable') } if (request.model !== undefined && request.provider === undefined) { - throw new Error('`model` requires `provider`') + throw new ToolArgsError(['`model` requires `provider`']) } if (request.provider === undefined) { const providers = llm.listProviders() @@ -69,11 +69,11 @@ async function listSubagentModels( ? '(no LLM providers)' : providers.map(provider => `${provider.id} — ${provider.name}`).join('\n') } - if (request.provider.length === 0) throw new Error('`provider` must be non-empty') + if (request.provider.length === 0) throw new ToolArgsError(['`provider` must be non-empty']) const allowedRoutes = policy.routes.filter(route => route.provider === request.provider) const [firstRoute] = allowedRoutes if (firstRoute === undefined) { - throw new Error(`LLM provider "${request.provider}" is not allowed for this Session`) + throw new SubagentError(`LLM provider "${request.provider}" is not allowed for this Session`, 'UNAUTHORIZED') } const provider = registeredProvider(llm, policy, request.provider) if (request.model === undefined) { @@ -85,9 +85,9 @@ async function listSubagentModels( ? `(no advertised models for ${provider.id})` : models.map(model => modelLine(provider.id, model)).join('\n') } - if (request.model.length === 0) throw new Error('`model` must be non-empty') + if (request.model.length === 0) throw new ToolArgsError(['`model` must be non-empty']) if (!allowedRoutes.some(route => route.model === request.model)) { - throw new Error(`child LLM route "${provider.id}/${request.model}" is not allowed for this Session`) + throw new SubagentError(`child LLM route "${provider.id}/${request.model}" is not allowed for this Session`, 'UNAUTHORIZED') } const model = await llm.resolveModelInfo(provider.id, request.model, signal) const efforts = model.reasoning?.efforts.map(effort => ( diff --git a/packages/subagent/tool-subagent/src/model-selection.ts b/packages/subagent/tool-subagent/src/model-selection.ts index cadeff0efe..7fa0da4c15 100644 --- a/packages/subagent/tool-subagent/src/model-selection.ts +++ b/packages/subagent/tool-subagent/src/model-selection.ts @@ -3,6 +3,8 @@ import { ReasoningEffortId } from '@deepseek-ai/dsh-llm' import type { LlmRuntime } from '@deepseek-ai/dsh-llm' import type { AgentOptions } from '@deepseek-ai/dsh-agent' +import { SubagentError } from '@deepseek-ai/dsh-subagent' +import { ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import z from '@deepseek-ai/schemastery' /** One exact child LLM route authorized by a user setting. */ @@ -82,7 +84,7 @@ export function hasDelegationModelRequest(request: DelegationModelRequest): bool /** Reject an empty model-facing route value at the tool JSON boundary. */ function assertNonEmpty(value: string | undefined, field: keyof DelegationModelRequest): void { if (value !== undefined && value.length === 0) { - throw new Error(`child LLM \`${field}\` must be non-empty`) + throw new ToolArgsError([`child LLM \`${field}\` must be non-empty`]) } } @@ -96,6 +98,9 @@ function assertNonEmpty(value: string | undefined, field: keyof DelegationModelR * @param policy - Session allowlist; omission permits only the current parent route. * @param parentOptions - Current parent route used when no policy is recorded. * @returns Child Agent options, preserving omission when no layer contributes one. + * @throws {SubagentError} `MODEL_SELECTION_DISABLED` when this tool instance + * forbids selection, or `UNAUTHORIZED` when the Session does not allow the route. + * @throws {ToolArgsError} when a field is empty or `provider` and `model` are not supplied together. */ export function requestedAgentOptions( configured: AgentOptions | undefined, @@ -106,15 +111,15 @@ export function requestedAgentOptions( ): AgentOptions | undefined { if (!hasDelegationModelRequest(request)) return configured if (!enabled) { - throw new Error('child model selection is disabled for this tool instance') + throw new SubagentError('child model selection is disabled for this tool instance', 'MODEL_SELECTION_DISABLED') } assertNonEmpty(request.provider, 'provider') assertNonEmpty(request.model, 'model') assertNonEmpty(request.reasoning_effort, 'reasoning_effort') if (request.provider === undefined || request.model === undefined) { - throw new Error(request.reasoning_effort === undefined + throw new ToolArgsError([request.reasoning_effort === undefined ? 'child LLM `provider` and `model` must be supplied together' - : 'child LLM `reasoning_effort` requires both `provider` and `model`; supply both or omit all three fields') + : 'child LLM `reasoning_effort` requires both `provider` and `model`; supply both or omit all three fields']) } assertAllowedModelSelection(policy, parentOptions, { provider: request.provider, model: request.model }) @@ -132,6 +137,7 @@ export function requestedAgentOptions( * @param policy - Session allowlist; omission permits only the current parent route. * @param parentOptions - Current parent route used when no policy is recorded. * @param route - Validated provider/model pair from the tool call. + * @throws {SubagentError} `UNAUTHORIZED` when the Session does not allow the route. */ export function assertAllowedModelSelection( policy: ModelSelectionPolicy | undefined, @@ -143,10 +149,10 @@ export function assertAllowedModelSelection( ? provider === parentOptions.provider && model === parentOptions.model : policy.routes.some(route => route.provider === provider && route.model === model) if (allowed) return - throw new Error(`child LLM route "${provider}/${model}" is not allowed for this Session` + throw new SubagentError(`child LLM route "${provider}/${model}" is not allowed for this Session` + (policy === undefined ? '; without a recorded model-selection policy, explicit selection is limited to the parent route' - : '')) + : ''), 'UNAUTHORIZED') } /** @@ -180,7 +186,7 @@ export async function preflightChildLlmRoute( const provider = requested?.provider ?? parentOptions.provider const model = requested?.model ?? parentOptions.model if (provider === undefined || model === undefined) { - throw new Error('cannot select child LLM values without an effective provider and model') + throw new ToolContextUnavailableError('cannot select child LLM values without an effective provider and model') } const routeChanged = provider !== parentOptions.provider || model !== parentOptions.model const reasoningEffort = requested?.reasoningEffort diff --git a/packages/subagent/tool-subagent/src/preset-selection.ts b/packages/subagent/tool-subagent/src/preset-selection.ts index 0bbb33f712..58da4a00e4 100644 --- a/packages/subagent/tool-subagent/src/preset-selection.ts +++ b/packages/subagent/tool-subagent/src/preset-selection.ts @@ -1,4 +1,5 @@ /** Deployment-owned preset choices for one delegation tool. */ +import { SubagentError } from '@deepseek-ai/dsh-subagent' import type { SubagentProvider } from '@deepseek-ai/dsh-subagent' /** Optional default and model-selectable preset ids for a spawn tool. */ @@ -59,13 +60,17 @@ export class SubagentPresetSelection { * Validate model input and apply the deployment default. * @param request - Model-supplied tool arguments. * @returns Selected preset id, or omission to inherit the parent. + * @throws {SubagentError} `PRESET_SELECTION_DISABLED` when this tool exposes no + * preset choice, or `PRESET_NOT_ALLOWED` when the id is outside the allowlist. */ resolve(request: PresetSelectionRequest): string | undefined { const id = request.agent_preset if (id === undefined) return this.config.agentPreset - if (this.choices === undefined) throw new Error('agent_preset selection is disabled for this tool instance') + if (this.choices === undefined) { + throw new SubagentError('agent_preset selection is disabled for this tool instance', 'PRESET_SELECTION_DISABLED') + } if (typeof id !== 'string' || !this.choices.includes(id)) { - throw new Error(`agent_preset must be one of: ${this.choices.join(', ')}`) + throw new SubagentError(`agent_preset must be one of: ${this.choices.join(', ')}`, 'PRESET_NOT_ALLOWED') } return id } diff --git a/packages/subagent/tool-subagent/tests/list-models.spec.ts b/packages/subagent/tool-subagent/tests/list-models.spec.ts index 654ab2f1b2..1bb3f053ba 100644 --- a/packages/subagent/tool-subagent/tests/list-models.spec.ts +++ b/packages/subagent/tool-subagent/tests/list-models.spec.ts @@ -177,7 +177,9 @@ describe('list_subagent_models', () => { await mountWorkingDirectoryFixture(ctx) await ctx.plugin(SubagentRuntime) await ctx.plugin(tool, { provider: 'unused', modelDiscovery: true }) - expect(text(await call(ctx, {}))).toContain('requires a calling agent') + const agentless = await call(ctx, {}) + expect(text(agentless)).toContain('requires a calling agent') + expect(agentless.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) await ctx.fiber.dispose() const parentContext = await setup({ provider: 'mock', withModelSelection: true, hostSelectionEnabled: false }) @@ -188,6 +190,7 @@ describe('list_subagent_models', () => { }) expect(result.isError).toBe(true) expect(text(result)).toContain('without a parent provider and model') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it('reads the recorded Session allowlist through the delegation plugin', async () => { @@ -217,6 +220,7 @@ describe('list_subagent_models', () => { const result = await call(ctx, {}) expect(result.isError).toBe(true) expect(text(result)).toContain('`llm` service is unavailable') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it('lists registered providers and follows live registration changes', async () => { @@ -259,6 +263,7 @@ describe('list_subagent_models', () => { const denied = await call(ctx, { provider: 'alpha', model: 'plain' }) expect(denied.isError).toBe(true) expect(text(denied)).toContain('is not allowed for this Session') + expect(denied.error?.info).toEqual({ name: 'SubagentError', code: 'UNAUTHORIZED' }) }) it('rejects an unauthorized provider before calling its adapter catalog', async () => { @@ -271,6 +276,7 @@ describe('list_subagent_models', () => { expect(result.isError).toBe(true) expect(text(result)).toContain('provider "secret" is not allowed for this Session') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'UNAUTHORIZED' }) expect(listModels).not.toHaveBeenCalled() }) @@ -376,14 +382,15 @@ describe('list_subagent_models', () => { }) it.each([ - { args: { model: 'fast' }, expected: '`model` requires `provider`' }, - { args: { provider: '' }, expected: '`provider` must be non-empty' }, - { args: { provider: 'missing' }, expected: 'is not allowed for this Session' }, - ])('rejects incomplete or unavailable provider requests', async ({ args, expected }) => { + { args: { model: 'fast' }, expected: '`model` requires `provider`', info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } }, + { args: { provider: '' }, expected: '`provider` must be non-empty', info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } }, + { args: { provider: 'missing' }, expected: 'is not allowed for this Session', info: { name: 'SubagentError', code: 'UNAUTHORIZED' } }, + ])('rejects incomplete or unavailable provider requests', async ({ args, expected, info }) => { const ctx = await setupListTool() const result = await call(ctx, args) expect(result.isError).toBe(true) expect(text(result)).toContain(expected) + expect(result.error?.info).toEqual(info) }) it('rejects an empty exact model after resolving the provider', async () => { @@ -392,6 +399,7 @@ describe('list_subagent_models', () => { const result = await call(ctx, { provider: 'alpha', model: '' }) expect(result.isError).toBe(true) expect(text(result)).toContain('`model` must be non-empty') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) }) it('reports registered alternatives for an unavailable provider', async () => { @@ -403,6 +411,7 @@ describe('list_subagent_models', () => { const result = await call(ctx, { provider: 'missing' }) expect(result.isError).toBe(true) expect(text(result)).toContain('available providers: alpha') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'NO_PROVIDER' }) expect(text(result)).not.toContain('secret') }) @@ -411,5 +420,6 @@ describe('list_subagent_models', () => { const result = await call(ctx, { provider: 'missing' }) expect(result.isError).toBe(true) expect(text(result)).toContain('available providers: (none)') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'NO_PROVIDER' }) }) }) diff --git a/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts b/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts index 5d26f6eb67..599fde1e79 100644 --- a/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts +++ b/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts @@ -285,6 +285,7 @@ describe('SubagentModelSelectionConfig', () => { expect(result.isError).toBe(true) expect(text(result)).toContain('is not allowed for this Session') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'UNAUTHORIZED' }) await ctx.fiber.dispose() }) diff --git a/packages/subagent/tool-subagent/tests/model-selection.spec.ts b/packages/subagent/tool-subagent/tests/model-selection.spec.ts index 014acf6d5b..9d8253ca80 100644 --- a/packages/subagent/tool-subagent/tests/model-selection.spec.ts +++ b/packages/subagent/tool-subagent/tests/model-selection.spec.ts @@ -119,6 +119,7 @@ describe('dsh-tool-subagent model selection', () => { }) expect(result.isError).toBe(true) expect(text(result)).toContain('model selection is disabled for this tool instance') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'MODEL_SELECTION_DISABLED' }) }) it('hides and rejects route fields without modelSelection', async () => { @@ -136,6 +137,7 @@ describe('dsh-tool-subagent model selection', () => { const result = await callSubagent(ctx, { description: 'forced route', prompt: 'do it', ...selection }) expect(result.isError).toBe(true) expect(text(result)).toContain('child model selection is disabled for this tool instance') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'MODEL_SELECTION_DISABLED' }) } }) @@ -173,6 +175,7 @@ describe('dsh-tool-subagent model selection', () => { }) expect(result.isError).toBe(true) expect(text(result)).toContain('`reasoning_effort` requires both `provider` and `model`') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) expect(start).not.toHaveBeenCalled() }) @@ -199,6 +202,7 @@ describe('dsh-tool-subagent model selection', () => { }) expect(result.isError).toBe(true) expect(text(result)).toContain('is not allowed for this Session') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'UNAUTHORIZED' }) }) it('discovers only the parent route without a Session policy and permits its explicit route and effort', async () => { @@ -403,12 +407,17 @@ describe('dsh-tool-subagent model selection', () => { }) expect(result.isError).toBe(true) expect(text(result)).toContain('`reasoning_effort` requires both `provider` and `model`') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) }) it('rejects preflight without an effective provider and model', async () => { const ctx = await setup({ provider: 'mock' }) await expect(preflightChildLlmRoute(ctx.llm, {}, undefined, AbortSignal.abort())) - .rejects.toThrow('without an effective provider and model') + .rejects.toMatchObject({ + name: 'ToolContextUnavailableError', + code: 'TOOL_CONTEXT_UNAVAILABLE', + message: 'cannot select child LLM values without an effective provider and model', + }) }) it.each([ @@ -420,6 +429,7 @@ describe('dsh-tool-subagent model selection', () => { const result = await callSubagent(ctx, { description: 'partial route', prompt: 'do it', ...route }) expect(result.isError).toBe(true) expect(text(result)).toContain('`provider` and `model` must be supplied together') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) expect(starts).toBe(0) }) @@ -432,6 +442,7 @@ describe('dsh-tool-subagent model selection', () => { const result = await callSubagent(ctx, { description: 'empty route', prompt: 'do it', ...selection }) expect(result.isError).toBe(true) expect(text(result)).toContain(expected) + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) }) it('uses the LLM runtime for provider and reasoning-effort validation before child creation', async () => { @@ -524,6 +535,7 @@ describe('dsh-tool-subagent model selection', () => { const configured = await callSubagent(ctx, { description: 'configured effort', prompt: 'do it' }, { agent: parentWithRoute() }) expect(configured.isError).toBe(true) expect(text(configured)).toContain('`llm` service is unavailable') + expect(configured.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) @@ -566,6 +578,7 @@ describe('dsh-tool-subagent model selection', () => { }) expect(denied.isError).toBe(true) expect(text(denied)).toContain('is not allowed for this Session') + expect(denied.error?.info).toEqual({ name: 'SubagentError', code: 'UNAUTHORIZED' }) const invalidEffort = await callSubagent(ctx, { description: 'unsupported effort', prompt: 'do it', provider: 'alpha', model: 'fast-model', reasoning_effort: 'invalid', @@ -599,6 +612,7 @@ describe('dsh-tool-subagent model selection', () => { const result = await callSubagent(ctx, { description: 'fork work', prompt: 'do it', ...selection }) expect(result.isError).toBe(true) expect(text(result)).toContain('model selection is disabled for this tool instance') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'MODEL_SELECTION_DISABLED' }) } expect(started).not.toHaveBeenCalled() diff --git a/packages/subagent/tool-subagent/tests/preset-selection.spec.ts b/packages/subagent/tool-subagent/tests/preset-selection.spec.ts index 636c88805e..9bfa7e9e85 100644 --- a/packages/subagent/tool-subagent/tests/preset-selection.spec.ts +++ b/packages/subagent/tool-subagent/tests/preset-selection.spec.ts @@ -98,6 +98,7 @@ describe('spawn preset selection', () => { const forced = await callSubagent(ctx, { ...args, agent_preset: 'writer' }) expect(forced.isError).toBe(true) expect(text(forced)).toContain('selection is disabled') + expect(forced.error?.info).toEqual({ name: 'SubagentError', code: 'PRESET_SELECTION_DISABLED' }) expect(onStart).toHaveBeenCalledTimes(1) }) @@ -134,8 +135,13 @@ describe('spawn preset selection', () => { it('rejects forced selection at the model JSON resolver', () => { const selection = new SubagentPresetSelection({ allowedAgentPresets: ['writer'] }) - expect(() => selection.resolve({ agent_preset: 'unlisted' })).toThrow(/must be one of/) - expect(() => selection.resolve({ agent_preset: 1 })).toThrow(/must be one of/) + for (const agent_preset of ['unlisted', 1]) { + expect(() => selection.resolve({ agent_preset })).toThrow(expect.objectContaining({ + name: 'SubagentError', + code: 'PRESET_NOT_ALLOWED', + message: 'agent_preset must be one of: writer', + })) + } }) it('requires the preset service when selection is configured', async () => { diff --git a/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts b/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts index 095d1de42c..6fcf375ad3 100644 --- a/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts +++ b/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts @@ -242,6 +242,7 @@ describe('dsh-tool-subagent', () => { const result = await pending expect(result.isError).toBe(true) expect(text(result)).toContain('changed while resolving the child LLM route') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'PROVIDER_CHANGED' }) expect(oldStart).not.toHaveBeenCalled() expect(replacementStart).not.toHaveBeenCalled() }) @@ -342,6 +343,7 @@ describe('dsh-tool-subagent', () => { const result = await callSubagent(ctx, { description: 'd', prompt: 'p' }, { agent: undefined }) expect(result.isError).toBe(true) expect(text(result)).toContain('requires a calling agent') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it('registers when the provider appears LATER — no load-order requirement (Loader starts siblings concurrently)', async () => { diff --git a/snapshots/session/subagent-depth-context-disabled/session.v4.jsonl b/snapshots/session/subagent-depth-context-disabled/session.v4.jsonl index 725da9a4cd..a85b1ef583 100644 --- a/snapshots/session/subagent-depth-context-disabled/session.v4.jsonl +++ b/snapshots/session/subagent-depth-context-disabled/session.v4.jsonl @@ -14,7 +14,7 @@ {"type":"session/title","data":{"title":"Attempt one subagent call beyond","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_depth_one_rejected","name":"subagent","arguments":"{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1789625678968,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1789625678968,"index":0,"dt":[],"id":"call_depth_one_rejected","name":"subagent","args":["{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\"}"]},{"type":"chunk","time":1789625678968,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_depth_one_rejected","name":"subagent","arguments":"{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\"}"}}},{"type":"chunk","time":1789625678968,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1789625678968,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_depth_one_rejected","name":"subagent","arguments":"{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\"}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_depth_one_rejected"},"toolCallId":"call_depth_one_rejected","content":[{"type":"text","text":"Error: subagent depth 1 exceeds maxDepth 0"}],"isError":true,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_depth_one_rejected"},"toolCallId":"call_depth_one_rejected","content":[{"type":"text","text":"Error: subagent depth 1 exceeds maxDepth 0"}],"isError":true,"id":"{{message:5}}"},"error":{"name":"SubagentDepthError","code":"DEPTH_EXCEEDED"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"DEPTH_REJECTED"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":10,"outputTokens":2},"stream":[{"type":"chunk","time":1789625678991,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1789625678991,"index":0,"dt":[],"texts":["DEPTH_REJECTED"]},{"type":"chunk","time":1789625678991,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DEPTH_REJECTED"}}},{"type":"chunk","time":1789625678991,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":2}}},{"type":"chunk","time":1789625678991,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl b/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl index a8dbd992e8..dfa91ecadc 100644 --- a/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl +++ b/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl @@ -15,7 +15,7 @@ {"type":"session/title","data":{"title":"Attempt one subagent call beyond","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_depth_three_rejected","name":"subagent","arguments":"{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\",\"run_in_background\":false}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:18}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1789625678968,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1789625678968,"index":0,"dt":[],"id":"call_depth_three_rejected","name":"subagent","args":["{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\",\"run_in_background\":false}"]},{"type":"chunk","time":1789625678968,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_depth_three_rejected","name":"subagent","arguments":"{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\",\"run_in_background\":false}"}}},{"type":"chunk","time":1789625678968,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1789625678968,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_depth_three_rejected","name":"subagent","arguments":"{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\",\"run_in_background\":false}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_depth_three_rejected"},"toolCallId":"call_depth_three_rejected","content":[{"type":"text","text":"Error: subagent depth 3 exceeds maxDepth 2"}],"isError":true,"id":"{{message:19}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_depth_three_rejected"},"toolCallId":"call_depth_three_rejected","content":[{"type":"text","text":"Error: subagent depth 3 exceeds maxDepth 2"}],"isError":true,"id":"{{message:19}}"},"error":{"name":"SubagentDepthError","code":"DEPTH_EXCEEDED"}},"sourceEventSeqs":[15],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"DEPTH_REJECTED"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:20}}"},"usage":{"inputTokens":10,"outputTokens":2},"stream":[{"type":"chunk","time":1789625678991,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1789625678991,"index":0,"dt":[],"texts":["DEPTH_REJECTED"]},{"type":"chunk","time":1789625678991,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DEPTH_REJECTED"}}},{"type":"chunk","time":1789625678991,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":2}}},{"type":"chunk","time":1789625678991,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/subagent-structured-parent/session.1.v4.jsonl b/snapshots/session/subagent-structured-parent/session.1.v4.jsonl index 5062e09793..9f3180e9f2 100644 --- a/snapshots/session/subagent-structured-parent/session.1.v4.jsonl +++ b/snapshots/session/subagent-structured-parent/session.1.v4.jsonl @@ -16,7 +16,7 @@ {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_structured_answer","name":"structured_output","arguments":"{\"answer\":41}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:11}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_structured_answer","name":"structured_output","arguments":"{\"answer\":41}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_structured_answer","name":"structured_output","arguments":"{\"answer\":41}"}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Correction: submit answer 42 instead."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:12}}"}]}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_structured_answer"},"toolCallId":"call_structured_answer","content":[{"type":"text","text":"Error: Process pending messages before submitting structured output."}],"isError":true,"id":"{{message:13}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_structured_answer"},"toolCallId":"call_structured_answer","content":[{"type":"text","text":"Error: Process pending messages before submitting structured output."}],"isError":true,"id":"{{message:13}}"},"error":{"name":"SubagentError","code":"STRUCTURED_OUTPUT_PENDING_INPUT"}},"sourceEventSeqs":[15],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":2}} From fdd2dcc7e87eb3a0da7c83f7144b8b740dd30d60 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:11:14 +0800 Subject: [PATCH 029/404] feat(plan-mode): add PlanModeError for exit_plan_mode failures exit_plan_mode threw plain Errors, so its most common failure, the user choosing to keep planning, reached tool/result without an error.code. PlanModeError carries PLAN_NOT_ACTIVE, PLAN_REVIEW_INTERRUPTED, and PLAN_REVISION_REQUESTED. A plan without a leading heading is a ToolArgsError, and a missing caller, user-questions channel, or projection reader is a ToolContextUnavailableError. Refs #7869 --- docs/subsystems/plan.i18n.yaml | 4 +- docs/subsystems/plan.md | 2 +- docs/subsystems/plan.zh.md | 2 +- packages/plan/plan-mode/README.i18n.yaml | 12 +++--- packages/plan/plan-mode/README.md | 5 ++- packages/plan/plan-mode/README.zh.md | 5 ++- packages/plan/plan-mode/src/error.ts | 38 +++++++++++++++++++ packages/plan/plan-mode/src/index.ts | 28 +++++++++----- .../plan/plan-mode/tests/plan-mode.spec.ts | 23 +++++++++-- snapshots/sdk/plan-review/session.v4.jsonl | 2 +- 10 files changed, 94 insertions(+), 27 deletions(-) create mode 100644 packages/plan/plan-mode/src/error.ts diff --git a/docs/subsystems/plan.i18n.yaml b/docs/subsystems/plan.i18n.yaml index 5e92dac5a5..f172403181 100644 --- a/docs/subsystems/plan.i18n.yaml +++ b/docs/subsystems/plan.i18n.yaml @@ -15,8 +15,8 @@ en: ee04468005fae8e1 zh: 1347d554102951f2 /plan-mode/the-exit-tool-and-the-plan-command: - en: 32ecfb7086dd1578 - zh: 0aaeaa69bb63f255 + en: c9e86f6312dab80f + zh: 41b763216d6b1a54 /plan-mode/the-service: en: f3e6d5a7fe0b67f0 zh: 774cc97e493991fa diff --git a/docs/subsystems/plan.md b/docs/subsystems/plan.md index a37207d868..05dbdc50a9 100644 --- a/docs/subsystems/plan.md +++ b/docs/subsystems/plan.md @@ -30,7 +30,7 @@ A missing, blank, or non-string `section` and any unknown key fail at plugin loa ## The exit tool and the `/plan` command -[`exit_plan_mode`](../tool-catalog.md#deepseek-aidsh-plan-mode) is disclosed progressively: it is admitted from the first step whose selected plan state is active and stays admitted for the rest of the Session, so the first plan-mode entry adds it to the request tool declarations and later transitions change only the plan guidance. Native and PTC execution use the same admitted set; a call before the first entry returns `UNKNOWN_TOOL`, and a call while plan mode is not committed fails. In plan mode it requires a complete markdown plan starting with a `#` heading and presents it for review through the [user-questions seam](user-questions.md). Approval returns `{ approved: true }` and records a silent (non-narrated) pending exit that is appended at the next accepted in-turn pre-step. Plan guidance therefore remains active for the rest of the assistant's current tool batch, and the tool result itself reports the transition. Keep-planning is a failed call carrying the user's feedback, so the model revises and presents again. A dismissed review returns `{ approved: false }` and concludes the turn, so plan mode stays active until the user's next message. A missing interaction channel and a service reload during review also fail the call rather than silently leaving plan mode. +[`exit_plan_mode`](../tool-catalog.md#deepseek-aidsh-plan-mode) is disclosed progressively: it is admitted from the first step whose selected plan state is active and stays admitted for the rest of the Session, so the first plan-mode entry adds it to the request tool declarations and later transitions change only the plan guidance. Native and PTC execution use the same admitted set; a call before the first entry returns `UNKNOWN_TOOL`, and a call while plan mode is not committed fails with `PlanModeError` `PLAN_NOT_ACTIVE`. In plan mode it requires a complete markdown plan starting with a `#` heading, rejecting any other plan with `ToolArgsError`, and presents it for review through the [user-questions seam](user-questions.md). Approval returns `{ approved: true }` and records a silent (non-narrated) pending exit that is appended at the next accepted in-turn pre-step. Plan guidance therefore remains active for the rest of the assistant's current tool batch, and the tool result itself reports the transition. Keep-planning is a failed call with `PlanModeError` `PLAN_REVISION_REQUESTED` carrying the user's feedback, so the model revises and presents again. A dismissed review returns `{ approved: false }` and concludes the turn, so plan mode stays active until the user's next message. A missing interaction channel (`ToolContextUnavailableError`) and a service reload during review (`PLAN_REVIEW_INTERRUPTED`) also fail the call rather than silently leaving plan mode. When [`ctx.commands`](commands.md) is composed, the plugin registers `/plan [off|message]`: bare `/plan` selects plan mode, any other non-empty message selects it and then submits the text through `agent.steer()` so it becomes the next step's ordinary logged user message under plan guidance, and the exact argument `off` selects inactive, which also cancels a pending entry before it is appended and becomes visible to a request. diff --git a/docs/subsystems/plan.zh.md b/docs/subsystems/plan.zh.md index 8f45d70c5b..de51ac0569 100644 --- a/docs/subsystems/plan.zh.md +++ b/docs/subsystems/plan.zh.md @@ -30,7 +30,7 @@ interface PlanModeConfig { ## 退出工具与 `/plan` 命令 -[`exit_plan_mode`](../tool-catalog.zh.md#deepseek-aidsh-plan-mode) 采用渐进式披露:从已选计划状态首次为激活的步骤起准入,并在会话剩余部分保持准入,因此首次进入计划模式时它进入请求的工具声明,之后的切换只改变计划指引。原生与 PTC 执行使用同一准入集合;首次进入之前调用返回 `UNKNOWN_TOOL`,计划模式未提交时调用会失败。在计划模式中,它要求一份以 `#` 标题开头的完整 markdown 计划,并通过[用户交互 seam](user-questions.zh.md) 呈交评审。批准返回 `{ approved: true }`,并记录一个静默(不叙述)的待生效退出,由下一个被接受的轮内 pre-step 追加。因此,计划指引在 assistant 当前这批工具调用的剩余部分继续生效,而工具结果本身会报告这次转换。「继续规划」则是一次携带用户反馈的失败调用,模型据此修订并再次呈交。放弃评审返回 `{ approved: false }` 并结束当前轮次,计划模式保持激活,直到用户发出下一条消息。评审期间交互通道缺失或服务重载同样使调用失败,而不是静默离开计划模式。 +[`exit_plan_mode`](../tool-catalog.zh.md#deepseek-aidsh-plan-mode) 采用渐进式披露:从已选计划状态首次为激活的步骤起准入,并在会话剩余部分保持准入,因此首次进入计划模式时它进入请求的工具声明,之后的切换只改变计划指引。原生与 PTC 执行使用同一准入集合;首次进入之前调用返回 `UNKNOWN_TOOL`,计划模式未提交时调用以 `PlanModeError` `PLAN_NOT_ACTIVE` 失败。在计划模式中,它要求一份以 `#` 标题开头的完整 markdown 计划,其他计划以 `ToolArgsError` 拒绝,并通过[用户交互 seam](user-questions.zh.md) 呈交评审。批准返回 `{ approved: true }`,并记录一个静默(不叙述)的待生效退出,由下一个被接受的轮内 pre-step 追加。因此,计划指引在 assistant 当前这批工具调用的剩余部分继续生效,而工具结果本身会报告这次转换。「继续规划」则是一次以 `PlanModeError` `PLAN_REVISION_REQUESTED` 失败并携带用户反馈的调用,模型据此修订并再次呈交。放弃评审返回 `{ approved: false }` 并结束当前轮次,计划模式保持激活,直到用户发出下一条消息。交互通道缺失(`ToolContextUnavailableError`)或评审期间服务重载(`PLAN_REVIEW_INTERRUPTED`)同样使调用失败,而不是静默离开计划模式。 当 [`ctx.commands`](commands.zh.md) 被组合时,插件注册 `/plan [off|message]`:单独的 `/plan` 选择计划模式;任何其他非空消息先选择计划模式,再通过 `agent.steer()` 提交该文本,使其在计划指引下成为下一步骤的普通已记录用户消息;确切参数 `off` 选择未激活,这还会在待生效条目被追加并对请求可见之前将其取消。 diff --git a/packages/plan/plan-mode/README.i18n.yaml b/packages/plan/plan-mode/README.i18n.yaml index 96b7f724c7..31f4436eec 100644 --- a/packages/plan/plan-mode/README.i18n.yaml +++ b/packages/plan/plan-mode/README.i18n.yaml @@ -45,14 +45,14 @@ en: a7bf35c2a9da52bc zh: dea9f4b3a41f1a6d /deepseek-ai-dsh-plan-mode/understand-the-implementation/the-exit-tool: - en: 7736aea9e4934fa8 - zh: a595e477f54a199e + en: d14383e9c8c404dc + zh: 056ec01db0f9d63e /deepseek-ai-dsh-plan-mode/understand-the-implementation/session-projection-unit: en: 396d66816890f715 zh: fab5d67c027b33f5 /deepseek-ai-dsh-plan-mode/understand-the-implementation/source-map: - en: fa97e858495a8105 - zh: 8be1fbd7e420ff8a + en: 5c25e9fd2b7104b8 + zh: 00af162e5a9d080a /deepseek-ai-dsh-plan-mode/further-exploration: en: 5008d6d632002f49 zh: 65184d489ecdcec0 @@ -90,8 +90,8 @@ en: 9622e96bdc01276d zh: 53801e68a49f3d1d /deepseek-ai-dsh-plan-mode/model-experience/exit-tool-schema-and-review-exchange/what-the-model-sees: - en: 1b978a7b6eecdffe - zh: 338000d1bf8dd4a9 + en: 7f132783f06161cf + zh: 571852401060940f /deepseek-ai-dsh-plan-mode/model-experience/exit-tool-schema-and-review-exchange/token-effect: en: 5ef9db72f91e4a8c zh: 6e96335cc3eb5976 diff --git a/packages/plan/plan-mode/README.md b/packages/plan/plan-mode/README.md index 0ea3a4b33c..38971a5c94 100644 --- a/packages/plan/plan-mode/README.md +++ b/packages/plan/plan-mode/README.md @@ -90,7 +90,7 @@ The command child activates only when a commands service is composed. It maps ba ### The exit tool -`exit_plan_mode` is disclosed progressively: it is admitted from the first step whose selected plan state is active and stays admitted for the rest of the Session, so entering plan mode the first time adds it together with the guidance, and later transitions change only the guidance; Native and PTC execution use the same admitted set. A call while plan mode is not committed fails. An approved review records a silent pending exit that the next accepted in-turn pre-step appends, keeping plan guidance for the rest of the current tool batch. Without a user-questions channel, or after a service reload while the review is pending, the call fails closed and `/plan off` remains the manual escape. +`exit_plan_mode` is disclosed progressively: it is admitted from the first step whose selected plan state is active and stays admitted for the rest of the Session, so entering plan mode the first time adds it together with the guidance, and later transitions change only the guidance; Native and PTC execution use the same admitted set. A call while plan mode is not committed fails with `PlanModeError` `PLAN_NOT_ACTIVE`, and a plan without a leading `#` heading fails with `ToolArgsError` before review. An approved review records a silent pending exit that the next accepted in-turn pre-step appends, keeping plan guidance for the rest of the current tool batch. Without a user-questions channel (`ToolContextUnavailableError`), or after a service reload while the review is pending (`PLAN_REVIEW_INTERRUPTED`), the call fails closed and `/plan off` remains the manual escape. [`src/error.ts`](src/error.ts) lists the `PlanModeError` codes. ### Session projection unit @@ -104,6 +104,7 @@ The unit turns logged `/plan` command runs into a candidate target, commits the |---|---| | [`src/index.ts`](src/index.ts) | Plugin entry: `Config` schema, the `ctx.planMode` service, `plan:policy` section, `/plan` command, `exit_plan_mode` tool | | [`src/types.ts`](src/types.ts) | The `plan` projection-key declaration and `PlanProjection` wire value | +| [`src/error.ts`](src/error.ts) | `PlanModeError` and its closed code list | | [`src/client.ts`](src/client.ts) | Client-namespace re-export of the types outlet | The review intent carries the originating tool-call id, so the Web client can reopen the same submitted plan after the review closes. The complete Markdown remains in the existing native call or PTC dispatch log. @@ -166,7 +167,7 @@ The user block is append-only conversation growth. Entering or leaving plan mode #### What the model sees -The [`exit_plan_mode` schema](../../../docs/tool-catalog.md#deepseek-aidsh-plan-mode) is offered from the first plan-mode entry in a Session; earlier calls return `UNKNOWN_TOOL`, calls after leaving plan mode fail as unavailable outside plan mode, and an approved in-mode review returns the canonical `{ approved: true }` value and renders the existing confirmation text. Rejection remains a failed call carrying review feedback. A dismissed review returns `{ approved: false }`, renders a note that the user will reply, and concludes the turn without another model request. +The [`exit_plan_mode` schema](../../../docs/tool-catalog.md#deepseek-aidsh-plan-mode) is offered from the first plan-mode entry in a Session; earlier calls return `UNKNOWN_TOOL`, calls after leaving plan mode fail as unavailable outside plan mode, and an approved in-mode review returns the canonical `{ approved: true }` value and renders the existing confirmation text. Rejection remains a failed call with `PLAN_REVISION_REQUESTED` carrying review feedback. A dismissed review returns `{ approved: false }`, renders a note that the user will reply, and concludes the turn without another model request. #### Token effect diff --git a/packages/plan/plan-mode/README.zh.md b/packages/plan/plan-mode/README.zh.md index 90ee3c97e5..76d43e43ec 100644 --- a/packages/plan/plan-mode/README.zh.md +++ b/packages/plan/plan-mode/README.zh.md @@ -90,7 +90,7 @@ agent 完成计划后,会以 markdown 形式、从标题开头书写计划并 ### 退出工具 -`exit_plan_mode` 采用渐进式披露:从已选计划状态首次为激活的步骤起准入,并在会话剩余部分保持准入,因此首次进入计划模式时它与指引一起出现,之后的切换只改变指引;原生与 PTC 执行使用同一准入集合。计划模式未提交时调用会失败。经批准的评审会记录一个静默的待生效退出,由下一个被接受的轮内 pre-step 追加,当前这批工具调用剩余部分仍保留计划引导。缺少用户交互通道,或评审等待期间服务重载,调用都会以拒绝方式失败,`/plan off` 仍是手动退路。 +`exit_plan_mode` 采用渐进式披露:从已选计划状态首次为激活的步骤起准入,并在会话剩余部分保持准入,因此首次进入计划模式时它与指引一起出现,之后的切换只改变指引;原生与 PTC 执行使用同一准入集合。计划模式未提交时调用以 `PlanModeError` `PLAN_NOT_ACTIVE` 失败,没有前导 `#` 标题的计划在评审前以 `ToolArgsError` 失败。经批准的评审会记录一个静默的待生效退出,由下一个被接受的轮内 pre-step 追加,当前这批工具调用剩余部分仍保留计划引导。缺少用户交互通道(`ToolContextUnavailableError`),或评审等待期间服务重载(`PLAN_REVIEW_INTERRUPTED`),调用都会以拒绝方式失败,`/plan off` 仍是手动退路。[`src/error.ts`](src/error.ts) 列出 `PlanModeError` 的 code。 ### 会话投影单元 @@ -104,6 +104,7 @@ agent 完成计划后,会以 markdown 形式、从标题开头书写计划并 |---|---| | [`src/index.ts`](src/index.ts) | 插件入口:`Config` schema、`ctx.planMode` 服务、`plan:policy` 段落、`/plan` 命令、`exit_plan_mode` 工具 | | [`src/types.ts`](src/types.ts) | `plan` 投影 key 声明与 `PlanProjection` 协议值 | +| [`src/error.ts`](src/error.ts) | `PlanModeError` 及其封闭 code 列表 | | [`src/client.ts`](src/client.ts) | types 出口的客户端命名空间再导出 | 审批意图携带发起工具调用的标识,让 Web 客户端在审批关闭后重新打开同一份计划。完整 Markdown 保留在已有的原生调用或 PTC dispatch 日志中。 @@ -166,7 +167,7 @@ You are in plan mode. Explore and design before presenting the complete plan thr #### 模型看到什么 -[`exit_plan_mode` schema](../../../docs/tool-catalog.zh.md#deepseek-aidsh-plan-mode) 从会话首次进入计划模式起提供;此前的调用返回 `UNKNOWN_TOOL`,离开计划模式后的调用会以计划模式之外不可用而失败。模式内获批的评审返回规范值 `{ approved: true }` 并渲染现有确认文本。拒绝仍是携带评审反馈的失败调用。放弃评审返回 `{ approved: false }`,渲染一条说明用户将自行回复的文本,并结束当前轮次,不再发起模型请求。 +[`exit_plan_mode` schema](../../../docs/tool-catalog.zh.md#deepseek-aidsh-plan-mode) 从会话首次进入计划模式起提供;此前的调用返回 `UNKNOWN_TOOL`,离开计划模式后的调用会以计划模式之外不可用而失败。模式内获批的评审返回规范值 `{ approved: true }` 并渲染现有确认文本。拒绝仍是以 `PLAN_REVISION_REQUESTED` 失败并携带评审反馈的调用。放弃评审返回 `{ approved: false }`,渲染一条说明用户将自行回复的文本,并结束当前轮次,不再发起模型请求。 #### Token 影响 diff --git a/packages/plan/plan-mode/src/error.ts b/packages/plan/plan-mode/src/error.ts new file mode 100644 index 0000000000..e0227893bb --- /dev/null +++ b/packages/plan/plan-mode/src/error.ts @@ -0,0 +1,38 @@ +/** + * Typed `exit_plan_mode` failures. + * + * @module @deepseek-ai/dsh-plan-mode/error + */ + +import { HarnessError } from '@deepseek-ai/dsh-llm' + +/** + * Every machine-routable plan-mode failure: + * - `PLAN_NOT_ACTIVE`: the caller's committed state is not plan mode; work without the exit tool. + * - `PLAN_REVIEW_INTERRUPTED`: the plan-mode service was reloaded during the review; present the plan again. + * - `PLAN_REVISION_REQUESTED`: the user chose to keep planning; revise the plan from the feedback in `message`. + */ +export const PLAN_MODE_ERROR_CODES = [ + 'PLAN_NOT_ACTIVE', + 'PLAN_REVIEW_INTERRUPTED', + 'PLAN_REVISION_REQUESTED', +] as const + +/** One plan-mode failure code. */ +export type PlanModeErrorCode = typeof PLAN_MODE_ERROR_CODES[number] + +/** Typed plan-mode failure; `code` is one of {@link PLAN_MODE_ERROR_CODES}. */ +export class PlanModeError extends HarnessError { + override readonly code: PlanModeErrorCode + + /** + * @param message - model-facing reason and next step. + * @param code - failure class from {@link PLAN_MODE_ERROR_CODES}. + * @param options - standard `cause` chaining. + */ + constructor(message: string, code: PlanModeErrorCode, options?: ErrorOptions) { + super(message, code, options) + this.name = 'PlanModeError' + this.code = code + } +} diff --git a/packages/plan/plan-mode/src/index.ts b/packages/plan/plan-mode/src/index.ts index 06af5c2828..636165c5e3 100644 --- a/packages/plan/plan-mode/src/index.ts +++ b/packages/plan/plan-mode/src/index.ts @@ -30,18 +30,20 @@ import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { ContextFormed } from '@deepseek-ai/dsh-llm' import type { Session, UserMessage } from '@deepseek-ai/dsh-session' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import { UserQuestionError, type AskUserQuestionAnswer } from '@deepseek-ai/dsh-user-questions' import type { CommandDefinitionId, CommandId } from '@deepseek-ai/dsh-commands' import type {} from '@deepseek-ai/dsh-session-projection' import type { ProjectionDefinition, ProjectionHandle } from '@deepseek-ai/dsh-session-projection' import type { PlanProjection, PlanUnitState } from './types.ts' +import { PlanModeError } from './error.ts' declare module '@deepseek-ai/dsh-llm' { interface MessageSourceMap { 'plan-mode': { kind: 'plan-mode' } & ContextFormed } } export type * from './types.ts' +export { PLAN_MODE_ERROR_CODES, PlanModeError, type PlanModeErrorCode } from './error.ts' declare module '@deepseek-ai/dsh-session/types' { interface SessionEventMap { @@ -301,15 +303,20 @@ export class PlanModeController extends Service { execute: async (args, exec) => { const agent = exec.agent // Admission outlives plan mode and follows the selected state, so check the committed state. - if (agent === undefined || !this.loggedActive(agent.session)) { - throw new Error(`${EXIT_PLAN_MODE} is only available in plan mode`) + if (agent === undefined) { + throw new ToolContextUnavailableError(`${EXIT_PLAN_MODE} requires a calling agent`) + } + if (!this.loggedActive(agent.session)) { + throw new PlanModeError(`${EXIT_PLAN_MODE} is only available in plan mode`, 'PLAN_NOT_ACTIVE') } if (!/^#\s+\S/.test(args.plan.trim())) { - throw new Error(`${EXIT_PLAN_MODE} requires a non-empty markdown plan starting with a # heading`) + throw new ToolArgsError([`${EXIT_PLAN_MODE} requires a non-empty markdown plan starting with a # heading`]) } const interaction = ctx.get('userQuestions') if (interaction === undefined) { - throw new Error('no user-questions channel is available to review the plan; ask the user to switch the session mode instead') + throw new ToolContextUnavailableError( + 'no user-questions channel is available to review the plan; ask the user to switch the session mode instead', + ) } let answer: AskUserQuestionAnswer try { @@ -345,15 +352,18 @@ export class PlanModeController extends Service { // A review may outlive this plugin fiber. Without its pre-step listener, // an approved selection could never be appended, so fail and keep planning. if (disposed) { - throw new Error('the plan-mode service was reloaded while the plan was under review; present the plan again') + throw new PlanModeError( + 'the plan-mode service was reloaded while the plan was under review; present the plan again', + 'PLAN_REVIEW_INTERRUPTED', + ) } const reviewItems = answer.answers.filter(entry => entry.id === REVIEW_ID) const item = reviewItems.length === 1 ? reviewItems[0] : undefined if (item?.selected.length !== 1 || item.selected[0] !== APPROVE_LABEL || item.custom !== undefined) { const feedback = item?.custom ?? '' - throw new Error(feedback === '' + throw new PlanModeError(feedback === '' ? 'The user chose to keep planning; revise the plan and present it again.' - : `The user chose to keep planning; their feedback: ${feedback}`) + : `The user chose to keep planning; their feedback: ${feedback}`, 'PLAN_REVISION_REQUESTED') } // Keep plan guidance for the rest of this assistant tool batch. The // silent selection is appended at the next accepted in-turn pre-step, @@ -394,7 +404,7 @@ export class PlanModeController extends Service { private planState(session: Session): PlanUnitState { if (this.planProjectionHandle === undefined) { - throw new Error('plan mode is not ready; await plugin activation before running an agent') + throw new ToolContextUnavailableError('plan mode is not ready; await plugin activation before running an agent') } return this.planProjectionHandle.stateOf(session) } diff --git a/packages/plan/plan-mode/tests/plan-mode.spec.ts b/packages/plan/plan-mode/tests/plan-mode.spec.ts index 99d72afd1d..0ebe17cb31 100644 --- a/packages/plan/plan-mode/tests/plan-mode.spec.ts +++ b/packages/plan/plan-mode/tests/plan-mode.spec.ts @@ -844,7 +844,11 @@ describe('exit_plan_mode', () => { arguments: { plan: '# P' }, token: Symbol('direct-exit') as ToolExecutionToken, signal: testToolSignal, deferContext() {}, concludeTurn() {}, } - await expect(exit?.execute({ plan: '# P' }, exec)).rejects.toThrow(`${EXIT_PLAN_MODE} is only available in plan mode`) + await expect(exit?.execute({ plan: '# P' }, exec)).rejects.toMatchObject({ + name: 'ToolContextUnavailableError', + code: 'TOOL_CONTEXT_UNAVAILABLE', + message: `${EXIT_PLAN_MODE} requires a calling agent`, + }) }) it('keeps the exit tool after leaving plan mode and rejects a call outside it', async () => { @@ -855,6 +859,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: exit_plan_mode is only available in plan mode' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_NOT_ACTIVE' }) }) it('admits the exit tool for a selected entry but rejects a call before the entry is logged', async () => { @@ -866,6 +871,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: exit_plan_mode is only available in plan mode' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_NOT_ACTIVE' }) }) it('rejects an empty or heading-less plan before asking the reviewer', async () => { @@ -873,7 +879,8 @@ describe('exit_plan_mode', () => { for (const plan of ['', 'do things']) { const result = await callExit(ctx, agent, plan) expect(result.isError).toBe(true) - expect(result.content).toEqual([{ type: 'text', text: 'Error: exit_plan_mode requires a non-empty markdown plan starting with a # heading' }]) + expect(result.content).toEqual([{ type: 'text', text: 'Error: invalid arguments: exit_plan_mode requires a non-empty markdown plan starting with a # heading' }]) + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) } expect(asked).toHaveLength(0) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) @@ -885,6 +892,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: no user-questions channel is available to review the plan; ask the user to switch the session mode instead' }]) + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) @@ -1022,6 +1030,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; their feedback: consider the resume path' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVISION_REQUESTED' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) @@ -1030,6 +1039,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; revise the plan and present it again.' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVISION_REQUESTED' }) }) it('a custom-text-only answer is feedback, never consent', async () => { @@ -1037,6 +1047,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; their feedback: add tests first' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVISION_REQUESTED' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) @@ -1045,6 +1056,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; revise the plan and present it again.' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVISION_REQUESTED' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) @@ -1053,6 +1065,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; their feedback: change the tests' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVISION_REQUESTED' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) @@ -1067,6 +1080,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; revise the plan and present it again.' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVISION_REQUESTED' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) @@ -1076,6 +1090,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; revise the plan and present it again.' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVISION_REQUESTED' }) }) it('declares the plan-review presentation intent naming its approve option', async () => { @@ -1153,6 +1168,7 @@ describe('exit_plan_mode', () => { const result = await pending expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: the plan-mode service was reloaded while the plan was under review; present the plan again' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVIEW_INTERRUPTED' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) @@ -1161,7 +1177,8 @@ describe('exit_plan_mode', () => { registerQuestionAnswerer(ctx, { ask: () => { throw new Error('review aborted') } }) const result = await callExit(ctx, agent) expect(result.isError).toBe(true) - expect(result.content).toEqual([{ type: 'text', text: 'Error: review aborted' }]) + expect(result.content).toEqual([{ type: 'text', text: 'Error: the user-questions answerer failed before the user answered' }]) + expect(result.error?.info).toEqual({ name: 'UserQuestionError', code: 'PROVIDER_ERROR' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) diff --git a/snapshots/sdk/plan-review/session.v4.jsonl b/snapshots/sdk/plan-review/session.v4.jsonl index 5911c994ea..5113b1bcc2 100644 --- a/snapshots/sdk/plan-review/session.v4.jsonl +++ b/snapshots/sdk/plan-review/session.v4.jsonl @@ -34,7 +34,7 @@ {"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:1}}","sessionFormatVersion":4,"throughSeq":31}} {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"commands-tool-1","name":"exit_plan_mode","arguments":"{\"plan\": \"# Implement the change\\n\\n- Inspect existing code.\\n- Make the smallest change.\\n- Run focused tests.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"tool-call"}]}},"id":"{{message:11}}"},"usage":{"inputTokens":10000,"outputTokens":32,"totalTokens":10032},"stream":[{"type":"chunk","time":1792108800000,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1792108800000,"index":0,"dt":[],"id":"commands-tool-1","name":"exit_plan_mode","args":[""]},{"type":"tool-call-chunks","time0":1792108800000,"index":0,"dt":[],"id":"commands-tool-1","args":["{\"plan\": \"# Implement the change\\n\\n- Inspect existing code.\\n- Make the smallest change.\\n- Run focused tests.\"}"]},{"type":"chunk","time":1792108800000,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"commands-tool-1","name":"exit_plan_mode","arguments":"{\"plan\": \"# Implement the change\\n\\n- Inspect existing code.\\n- Make the smallest change.\\n- Run focused tests.\"}"}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"usage","usage":{"inputTokens":10000,"outputTokens":32,"totalTokens":10032}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"finish","reason":{"kind":"tool-calls"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"tool-call"}]}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":2,"step":1,"callId":"commands-tool-1","name":"exit_plan_mode","arguments":"{\"plan\": \"# Implement the change\\n\\n- Inspect existing code.\\n- Make the smallest change.\\n- Run focused tests.\"}"}} -{"type":"tool/result","data":{"turn":2,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"commands-tool-1"},"toolCallId":"commands-tool-1","content":[{"type":"text","text":"Error: The user chose to keep planning; their feedback: Add rollback."}],"isError":true,"id":"{{message:12}}"}},"sourceEventSeqs":[34],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":2,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"commands-tool-1"},"toolCallId":"commands-tool-1","content":[{"type":"text","text":"Error: The user chose to keep planning; their feedback: Add rollback."}],"isError":true,"id":"{{message:12}}"},"error":{"name":"PlanModeError","code":"PLAN_REVISION_REQUESTED"}},"sourceEventSeqs":[34],"surfaceOp":"append"} {"type":"step/end","data":{"turn":2,"step":1}} {"type":"step/start","data":{"turn":2,"step":2}} {"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:1}}","sessionFormatVersion":4,"throughSeq":37}} From 551e5ce51a88b92c400f54bcd1e7c243f26045fc Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:11:15 +0800 Subject: [PATCH 030/404] feat(workflow): code workflow runs that end cancelled or failed The workflow tool threw a plain Error when a foreground run settled as cancelled or error, the most frequent uncoded workflow failure. It now throws WorkflowError CANCELLED or the new RUN_FAILED code, and rethrows the caller's abort reason when the calling step was aborted so the registry records AbortError ABORTED. A disabled run_in_background is UNSUPPORTED_OPTION, and a missing caller or jobs service is a ToolContextUnavailableError. Refs #7869 --- docs/subsystems/workflow.i18n.yaml | 4 +-- docs/subsystems/workflow.md | 2 +- docs/subsystems/workflow.zh.md | 2 +- .../workflow/tool-workflow/README.i18n.yaml | 12 ++++----- packages/workflow/tool-workflow/README.md | 6 ++--- packages/workflow/tool-workflow/README.zh.md | 6 ++--- packages/workflow/tool-workflow/src/index.ts | 27 ++++++++++--------- .../tool-workflow/tests/tool-workflow.spec.ts | 10 +++++-- packages/workflow/workflow/README.i18n.yaml | 4 +-- packages/workflow/workflow/README.md | 2 +- packages/workflow/workflow/README.zh.md | 2 +- packages/workflow/workflow/src/index.ts | 7 +++-- 12 files changed, 48 insertions(+), 36 deletions(-) diff --git a/docs/subsystems/workflow.i18n.yaml b/docs/subsystems/workflow.i18n.yaml index f3b906de0d..fdd069e032 100644 --- a/docs/subsystems/workflow.i18n.yaml +++ b/docs/subsystems/workflow.i18n.yaml @@ -18,8 +18,8 @@ en: a86b204323005042 zh: 82b691e28ed4dcd3 /workflow/failure-discipline-workflowerror-fatal: - en: 4d390801bb07374c - zh: 1099f053c2ee26ec + en: b53ef6f97fb9c092 + zh: 5a34538bff77e364 /workflow/events: en: de123821a128c1d1 zh: e50bcaea2812575a diff --git a/docs/subsystems/workflow.md b/docs/subsystems/workflow.md index 5b51dc1ff1..7b84c7f33b 100644 --- a/docs/subsystems/workflow.md +++ b/docs/subsystems/workflow.md @@ -113,7 +113,7 @@ interface WorkflowRun { ## Failure discipline: `WorkflowError.fatal` -Hook misuse inside a script — bad arguments, unknown/deferred `agent()` options, a schema outside the [structured-output subset](../../packages/core/tools/README.md), a tripped cap, a seam start failure, cancellation — throws a `WorkflowError` with `fatal: true`. The `parallel()`/`pipeline()` combinators RE-THROW fatal errors instead of mapping the item to `null`: a typo'd option must kill the script loudly, never dissolve into something that reads as an ordinary child failure. The per-item `null` is reserved for child-run failures (a non-`completed` stop reason) and ordinary in-stage script errors. +Hook misuse inside a script — bad arguments, unknown/deferred `agent()` options, a schema outside the [structured-output subset](../../packages/core/tools/README.md), a tripped cap, a seam start failure, cancellation — throws a `WorkflowError` with `fatal: true`. The `parallel()`/`pipeline()` combinators RE-THROW fatal errors instead of mapping the item to `null`: a typo'd option must kill the script loudly, never dissolve into something that reads as an ordinary child failure. The per-item `null` is reserved for child-run failures (a non-`completed` stop reason) and ordinary in-stage script errors. Because `WorkflowResult` carries only the failure message, the `workflow` tool classifies a run that settled as `cancelled` with `CANCELLED` and one that settled as `error` with `RUN_FAILED`; when the calling step itself was aborted, the tool runtime's `AbortError` `ABORTED` result applies instead. ## Events diff --git a/docs/subsystems/workflow.zh.md b/docs/subsystems/workflow.zh.md index 1514fa31d6..56e3a0ff22 100644 --- a/docs/subsystems/workflow.zh.md +++ b/docs/subsystems/workflow.zh.md @@ -113,7 +113,7 @@ interface WorkflowRun { ## 失败纪律:`WorkflowError.fatal` -脚本内部的钩子误用:错误参数、未知或延迟的 `agent()` 选项、超出[结构化输出子集](../../packages/core/tools/README.zh.md)的 schema、超出上限、seam 启动失败、取消,都会抛出 `fatal: true` 的 `WorkflowError`。`parallel()`/`pipeline()` 组合器对 fatal 错误直接重新抛出,而非将该项映射为 `null`:一个拼写错误的选项必须明确报错并终止脚本,绝不能消融为看似普通子 agent 失败的结果。逐项的 `null` 保留给子运行失败(非 `completed` 的 stop reason)和阶段内的普通脚本错误。 +脚本内部的钩子误用:错误参数、未知或延迟的 `agent()` 选项、超出[结构化输出子集](../../packages/core/tools/README.zh.md)的 schema、超出上限、seam 启动失败、取消,都会抛出 `fatal: true` 的 `WorkflowError`。`parallel()`/`pipeline()` 组合器对 fatal 错误直接重新抛出,而非将该项映射为 `null`:一个拼写错误的选项必须明确报错并终止脚本,绝不能消融为看似普通子 agent 失败的结果。逐项的 `null` 保留给子运行失败(非 `completed` 的 stop reason)和阶段内的普通脚本错误。由于 `WorkflowResult` 只携带失败消息,`workflow` 工具把以 `cancelled` 结束的运行归类为 `CANCELLED`,把以 `error` 结束的运行归类为 `RUN_FAILED`;调用方步骤本身被中止时,改为使用工具运行时的 `AbortError` `ABORTED` 结果。 ## 事件 diff --git a/packages/workflow/tool-workflow/README.i18n.yaml b/packages/workflow/tool-workflow/README.i18n.yaml index 8f307582b3..0fd0d3a6ed 100644 --- a/packages/workflow/tool-workflow/README.i18n.yaml +++ b/packages/workflow/tool-workflow/README.i18n.yaml @@ -18,8 +18,8 @@ en: a0a9d655187f285d zh: 230b4556fff9f08b /deepseek-ai-dsh-tool-workflow/use-this-package/calling-the-tool: - en: aeebba9469f0558d - zh: e2e74d4272e94201 + en: 8b9606845ce5caf1 + zh: af0b71be80e1bb7c /deepseek-ai-dsh-tool-workflow/use-this-package/what-to-expect-during-a-run: en: 19ec4f830edb8e1a zh: 8579ae5274aca6de @@ -36,8 +36,8 @@ en: 6d09119d1393c254 zh: a7cc03daa59650ec /deepseek-ai-dsh-tool-workflow/understand-the-implementation/run-lifecycle: - en: 8ea9ce564251249a - zh: a59b88cc14a25a1f + en: ef2c2a573b30c262 + zh: 5a078b9fe31e333d /deepseek-ai-dsh-tool-workflow/understand-the-implementation/background-lifecycle: en: 35950b2015800ec5 zh: 5ae6f5a5e53dc585 @@ -87,8 +87,8 @@ en: 9717b983b6a857e3 zh: 611a2dadf7c0c706 /deepseek-ai-dsh-tool-workflow/model-experience/tool-call-history-and-result/what-the-model-sees: - en: acd5e87161ced588 - zh: 5ffe85926ee1b88d + en: 483515bf4c1dc710 + zh: 69b23bd7f331ddea /deepseek-ai-dsh-tool-workflow/model-experience/tool-call-history-and-result/token-effect: en: 88cfc89c7dc19dbb zh: 75e674844f311937 diff --git a/packages/workflow/tool-workflow/README.md b/packages/workflow/tool-workflow/README.md index 5cdadb9ab5..7dc859d1f2 100644 --- a/packages/workflow/tool-workflow/README.md +++ b/packages/workflow/tool-workflow/README.md @@ -31,7 +31,7 @@ The `workflow` tool runs a model-authored orchestration script that fans work ou The model submits three parameters plus one flag: `meta` (required identity data: `name`, `description`, and optional `whenToUse` and `phases`), `script` (required plain JavaScript body — no `export const meta` statement; its parameter description carries the body rules and the tool description carries the hook contract), `args` (optional JSON object exposed to the script as the `args` global; wrap a bare list in a field so the wire schema stays honest), and `run_in_background` (optional; present only while `enableRunInBackground` holds). -A foreground success returns the envelope `{ kind: 'foreground', runId, agentsStarted, result }`, rendered to the model as `workflow "" completed ( agent).` followed by `Return value:` and the pretty-printed JSON. A workflow that cannot start — a script parse or meta validation failure — returns an error the model can correct from. Cancellation and execution failures return `Error: workflow run was cancelled` or `Error: workflow run failed: `; partial output is never reported as success. +A foreground success returns the envelope `{ kind: 'foreground', runId, agentsStarted, result }`, rendered to the model as `workflow "" completed ( agent).` followed by `Return value:` and the pretty-printed JSON. A workflow that cannot start — a script parse or meta validation failure — returns an error the model can correct from. Cancelling the calling step returns the tool runtime's `AbortError` `ABORTED` result; any other cancellation and execution failures return `Error: workflow run was cancelled` (`WorkflowError` `CANCELLED`) or `Error: workflow run failed: ` (`WorkflowError` `RUN_FAILED`); partial output is never reported as success. ### What to expect during a run @@ -67,7 +67,7 @@ The consumer owns the model-facing schema, the `tool:` system-prompt g ### Run lifecycle -`execute` starts the run and awaits `run.result` inside a `try/finally` that always disposes the run. `exec.signal` is bridged to `run.cancel()`, including the already-aborted-before-start case. A non-`completed` stop reason maps to an `isError` result reporting the reason; completion renders `{ kind, runId, agentsStarted, result }`, with the Native renderer truncating only that projection at `maxResultChars`. +`execute` starts the run and awaits `run.result` inside a `try/finally` that always disposes the run. `exec.signal` is bridged to `run.cancel()`, including the already-aborted-before-start case. A non-`completed` stop reason maps to an `isError` result reporting the reason, rethrowing the caller's abort reason when `exec.signal` aborted and otherwise throwing a `WorkflowError`; completion renders `{ kind, runId, agentsStarted, result }`, with the Native renderer truncating only that projection at `maxResultChars`. ### Background lifecycle @@ -150,7 +150,7 @@ Prefix-stable while `toolName`, definition, and visibility are unchanged. Renami #### What the model sees -The full model-written script, metadata, and args remain in the assistant tool call. A foreground success is exactly `workflow "" completed ( agent).`, newline, `Return value:`, newline, and pretty-printed data-dependent JSON; a cap adds `… [truncated: more characters]` on a new line. A background acceptance is exactly `workflow "" started in the background as job . Its return value arrives with the completion notice; check on it with job_output, stop it with job_kill.`, and the same rendered value later reaches the model through the job's completion notice and `job_output`. Failures are exactly `Error: workflow run was cancelled`, optionally suffixed ` ()`, `Error: workflow run failed: `, or defensively `Error: workflow run ended abnormally ()`; a call without an owning agent becomes `Error: workflow tool requires a calling agent (exec.agent was undefined)`. Intermediate child messages are omitted. +The full model-written script, metadata, and args remain in the assistant tool call. A foreground success is exactly `workflow "" completed ( agent).`, newline, `Return value:`, newline, and pretty-printed data-dependent JSON; a cap adds `… [truncated: more characters]` on a new line. A background acceptance is exactly `workflow "" started in the background as job . Its return value arrives with the completion notice; check on it with job_output, stop it with job_kill.`, and the same rendered value later reaches the model through the job's completion notice and `job_output`. Failures after a caller abort render the abort reason; other failures are exactly `Error: workflow run was cancelled`, optionally suffixed ` ()`, `Error: workflow run failed: `, or defensively `Error: workflow run ended abnormally ()`; a call without an owning agent becomes `Error: workflow tool requires a calling agent (exec.agent was undefined)` (`ToolContextUnavailableError`). Intermediate child messages are omitted. #### Token effect diff --git a/packages/workflow/tool-workflow/README.zh.md b/packages/workflow/tool-workflow/README.zh.md index dcc92b352c..5b9ebe44c1 100644 --- a/packages/workflow/tool-workflow/README.zh.md +++ b/packages/workflow/tool-workflow/README.zh.md @@ -31,7 +31,7 @@ kind: "package-reference" 模型提交三个参数外加一个开关:`meta`(必需的身份数据:`name`、`description`,以及可选的 `whenToUse` 与 `phases`)、`script`(必需的纯 JavaScript 脚本体——不含 `export const meta` 语句;其参数描述携带脚本体规则,工具描述携带钩子约定)、`args`(可选 JSON 对象,作为全局变量 `args` 向脚本公开;裸列表应包装到字段中,使协议 schema 如实表达形态),以及 `run_in_background`(可选;仅在 `enableRunInBackground` 生效时存在)。 -前台成功返回包络 `{ kind: 'foreground', runId, agentsStarted, result }`,向模型渲染为 `workflow "" completed ( agent).`,后接 `Return value:` 与美化打印的 JSON。无法启动的工作流——脚本解析或 meta 校验失败——返回模型可以修正的错误。取消与执行失败返回 `Error: workflow run was cancelled` 或 `Error: workflow run failed: `;部分输出绝不会被报告为成功。 +前台成功返回包络 `{ kind: 'foreground', runId, agentsStarted, result }`,向模型渲染为 `workflow "" completed ( agent).`,后接 `Return value:` 与美化打印的 JSON。无法启动的工作流——脚本解析或 meta 校验失败——返回模型可以修正的错误。取消调用方步骤时返回工具运行时的 `AbortError` `ABORTED` 结果;其他取消与执行失败返回 `Error: workflow run was cancelled`(`WorkflowError` `CANCELLED`)或 `Error: workflow run failed: `(`WorkflowError` `RUN_FAILED`);部分输出绝不会被报告为成功。 ### 运行期间的预期 @@ -67,7 +67,7 @@ kind: "package-reference" ### 运行生命周期 -`execute` 启动运行,并在 `try/finally` 内等待 `run.result`;该结构总会对运行执行 dispose。`exec.signal` 会桥接到 `run.cancel()`,包括启动前已经中止的情况。非 `completed` 结束原因会映射为报告原因的 `isError` 结果;完成时渲染 `{ kind, runId, agentsStarted, result }`,Native 渲染器只会在 `maxResultChars` 处截断该投影。 +`execute` 启动运行,并在 `try/finally` 内等待 `run.result`;该结构总会对运行执行 dispose。`exec.signal` 会桥接到 `run.cancel()`,包括启动前已经中止的情况。非 `completed` 结束原因会映射为报告原因的 `isError` 结果:`exec.signal` 已中止时重新抛出调用方的中止原因,否则抛出 `WorkflowError`;完成时渲染 `{ kind, runId, agentsStarted, result }`,Native 渲染器只会在 `maxResultChars` 处截断该投影。 ### 后台生命周期 @@ -150,7 +150,7 @@ Use the tool ONLY when the user explicitly asks for a workflow or for #### 模型看到什么 -由模型编写的完整脚本、元数据与 args 会保留在 assistant 工具调用中。前台成功结果精确为 `workflow "" completed ( agent).`、换行、`Return value:`、换行,以及美化打印且依赖数据的 JSON;达到上限时,会在新行添加 `… [truncated: more characters]`。后台受理结果精确为 `workflow "" started in the background as job . Its return value arrives with the completion notice; check on it with job_output, stop it with job_kill.`,同样渲染的值稍后经任务完成播报与 `job_output` 抵达模型。失败结果精确为 `Error: workflow run was cancelled`(可以追加后缀 ` ()`)、`Error: workflow run failed: ` 或防御性的 `Error: workflow run ended abnormally ()`;没有所属 agent 的调用变为 `Error: workflow tool requires a calling agent (exec.agent was undefined)`。中间子 agent 消息会被省略。 +由模型编写的完整脚本、元数据与 args 会保留在 assistant 工具调用中。前台成功结果精确为 `workflow "" completed ( agent).`、换行、`Return value:`、换行,以及美化打印且依赖数据的 JSON;达到上限时,会在新行添加 `… [truncated: more characters]`。后台受理结果精确为 `workflow "" started in the background as job . Its return value arrives with the completion notice; check on it with job_output, stop it with job_kill.`,同样渲染的值稍后经任务完成播报与 `job_output` 抵达模型。调用方中止后的失败渲染中止原因;其他失败结果精确为 `Error: workflow run was cancelled`(可以追加后缀 ` ()`)、`Error: workflow run failed: ` 或防御性的 `Error: workflow run ended abnormally ()`;没有所属 agent 的调用变为 `Error: workflow tool requires a calling agent (exec.agent was undefined)`(`ToolContextUnavailableError`)。中间子 agent 消息会被省略。 #### Token 影响 diff --git a/packages/workflow/tool-workflow/src/index.ts b/packages/workflow/tool-workflow/src/index.ts index 66fda2da15..c8e3135c1c 100644 --- a/packages/workflow/tool-workflow/src/index.ts +++ b/packages/workflow/tool-workflow/src/index.ts @@ -14,13 +14,14 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { ToolCallView, ToolResultView } from '@deepseek-ai/dsh-tools' import type { Agent } from '@deepseek-ai/dsh-agent' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import type { JobId, JobOutcome, JobToolCall } from '@deepseek-ai/dsh-jobs' import type { Session, SessionEventMap } from '@deepseek-ai/dsh-session' import type { JsonValue } from '@deepseek-ai/dsh-util-values' +import { WorkflowError } from '@deepseek-ai/dsh-workflow' import type { WorkflowResult, WorkflowRun, WorkflowRunId, WorkflowStopReason, } from '@deepseek-ai/dsh-workflow' @@ -194,17 +195,17 @@ function presentWorkflowResult(args: WorkflowCallArgs, result: { content: Conten } /** A non-`completed` stop reason means the script did not finish cleanly. */ -function stopReasonError(result: WorkflowResult): string | undefined { +function stopReasonError(result: WorkflowResult): WorkflowError | undefined { switch (result.stopReason) { case 'completed': return undefined case 'cancelled': - return `workflow run was cancelled${result.error !== undefined ? ` (${result.error})` : ''}` + return new WorkflowError(`workflow run was cancelled${result.error !== undefined ? ` (${result.error})` : ''}`, 'CANCELLED') case 'error': - return `workflow run failed: ${result.error ?? 'unknown error'}` + return new WorkflowError(`workflow run failed: ${result.error ?? 'unknown error'}`, 'RUN_FAILED') /* v8 ignore start -- defensive: WorkflowStopReason is a closed union, exhaustive by construction; a future variant fails here loudly */ default: - return `workflow run ended abnormally (${String(result.stopReason satisfies never)})` + return new WorkflowError(`workflow run ended abnormally (${String(result.stopReason satisfies never)})`, 'RUN_FAILED') /* v8 ignore stop */ } } @@ -270,7 +271,7 @@ function startBackgroundRun( ): { kind: 'background'; jobId: JobId; runId: WorkflowRunId } { const jobs = ctx.get('jobs') if (jobs === undefined) { - throw new Error('background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs') + throw new ToolContextUnavailableError('background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs') } let run!: WorkflowRun const jobId = jobs.start({ @@ -412,11 +413,11 @@ export function apply(ctx: Context, config: Config): void { // The loop sets `exec.agent` for every model-driven call; its absence // means a non-agent caller invoked the tool directly, which has no // parent to attribute the children to. Fail loud rather than guess. - throw new Error('workflow tool requires a calling agent (exec.agent was undefined)') + throw new ToolContextUnavailableError('workflow tool requires a calling agent (exec.agent was undefined)') } if (args.run_in_background === true) { if (!enableRunInBackground) { - throw new Error('run_in_background is disabled for this tool') + throw new WorkflowError('run_in_background is disabled for this tool', 'UNSUPPORTED_OPTION') } // No pre-abort check here, unlike bash/pwsh: ToolRuntime re-reads the // caller signal right before execute(), and this branch reaches @@ -455,9 +456,11 @@ export function apply(ctx: Context, config: Config): void { result = await run.result const error = stopReasonError(result) if (error !== undefined) { - // Map a non-clean finish to an isError result (the registry turns a - // throw into an isError). Report the reason, not partial output. - throw new Error(error) + // Caller cancellation keeps the registry's AbortError identity; any + // other non-clean finish becomes a coded isError result. Report the + // reason, not partial output. + exec.signal.throwIfAborted() + throw error } return { kind: 'foreground' as const, @@ -473,7 +476,7 @@ export function apply(ctx: Context, config: Config): void { await run.dispose() if (recordsRun) { /* v8 ignore next -- WorkflowRun.result never rejects by contract, so result is assigned before finally. */ - if (result === undefined) throw new Error('workflow run settled without a result') + if (result === undefined) throw new WorkflowError('workflow run settled without a result', 'RUN_FAILED') recorder.finish(run.id, result.stopReason) } } finally { diff --git a/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts b/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts index 1502b428cd..98ea14d105 100644 --- a/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts +++ b/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts @@ -5,7 +5,7 @@ import { describe, expect, it, onTestFinished, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' -import ToolRuntime, { TOOL_ABORTED_BEFORE_DISPATCH } from '@deepseek-ai/dsh-tools' +import ToolRuntime, { TOOL_ABORTED, TOOL_ABORTED_BEFORE_DISPATCH } from '@deepseek-ai/dsh-tools' import type { ToolExecutionResult, ToolExecutionToken } from '@deepseek-ai/dsh-tools' import type { Agent } from '@deepseek-ai/dsh-agent' import { WorkflowRunId, WorkflowEngine } from '@deepseek-ai/dsh-workflow' @@ -303,6 +303,7 @@ describe('dsh-tool-workflow', () => { const result = await pending expect(result.isError).toBe(true) expect((result.content[0] as { text: string }).text).toContain('workflow run failed: script threw: boom') + expect(result.error?.info).toEqual({ name: 'WorkflowError', code: 'RUN_FAILED' }) expect(engine.disposed).toBe(1) }) @@ -314,6 +315,7 @@ describe('dsh-tool-workflow', () => { const result = await pending expect(result.isError).toBe(true) expect((result.content[0] as { text: string }).text).toContain('workflow run was cancelled (user)') + expect(result.error?.info).toEqual({ name: 'WorkflowError', code: 'CANCELLED' }) const bare = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent }) await vi.waitFor(() => { expect(engine.requests.length).toBe(2) }) @@ -337,6 +339,7 @@ describe('dsh-tool-workflow', () => { controller.abort() const result = await pending expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'AbortError', code: TOOL_ABORTED }) expect(engine.cancels).toContain('parent step aborted') expect(engine.disposed).toBe(1) }) @@ -354,6 +357,7 @@ describe('dsh-tool-workflow', () => { const result = await execute(ctx, { script: SCRIPT, meta: META }) expect(result.isError).toBe(true) expect((result.content[0] as { text: string }).text).toContain('requires a calling agent') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) expect(engine.requests.length).toBe(0) }) @@ -614,6 +618,7 @@ describe('dsh-tool-workflow', () => { expect(result.isError).toBe(true) expect((result.content[0] as { text: string }).text) .toContain('background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it('a disabled composition hides the parameter and rejects the call', async () => { @@ -624,6 +629,7 @@ describe('dsh-tool-workflow', () => { const result = await execute(ctx, { script: SCRIPT, meta: META, run_in_background: true }, { agent: parent }) expect(result.isError).toBe(true) expect((result.content[0] as { text: string }).text).toContain('run_in_background is disabled') + expect(result.error?.info).toEqual({ name: 'WorkflowError', code: 'UNSUPPORTED_OPTION' }) }) it('advertises the background semantics in the parameter', async () => { @@ -665,7 +671,7 @@ describe('dsh-tool-workflow', () => { controller.abort('user abort') const result = await pending expect(result.isError).toBe(true) - expect((result.content[0] as { text: string }).text).toContain('cancelled') + expect(result.error?.info).toEqual({ name: 'AbortError', code: TOOL_ABORTED }) }) it('a background run over the sandboxed PTC engine settles its job with the rendered return value', async () => { diff --git a/packages/workflow/workflow/README.i18n.yaml b/packages/workflow/workflow/README.i18n.yaml index dbd14da4fe..5760add38c 100644 --- a/packages/workflow/workflow/README.i18n.yaml +++ b/packages/workflow/workflow/README.i18n.yaml @@ -42,8 +42,8 @@ en: 95b074d816b52323 zh: dfa070a1531651f9 /deepseek-ai-dsh-workflow/understand-the-implementation/failure-discipline: - en: e2c2a6e2876457e8 - zh: 764cba9eede4bb79 + en: 8b862e7714718ba4 + zh: 21a04481ea85ff52 /deepseek-ai-dsh-workflow/further-exploration: en: 6b3752bee67372c3 zh: 92492c01c4d786d3 diff --git a/packages/workflow/workflow/README.md b/packages/workflow/workflow/README.md index 0bf762913f..0c3c5650f1 100644 --- a/packages/workflow/workflow/README.md +++ b/packages/workflow/workflow/README.md @@ -86,7 +86,7 @@ A run is holder-owned: engine-plugin unload prevents new starts but does not rev ### Failure discipline -`WorkflowError` carries a machine-routable code and a `fatal` flag; every code is fatal, and `parallel()` and `pipeline()` re-throw fatal errors instead of mapping the item to `null` — a typo'd option must kill the script loudly. Codes cover start failures, contract violations, exceeded caps, provider and result faults, unserializable values, and cancellation; the exact set and meanings live in [`src/index.ts`](src/index.ts). +`WorkflowError` carries a machine-routable code and a `fatal` flag; every code is fatal, and `parallel()` and `pipeline()` re-throw fatal errors instead of mapping the item to `null` — a typo'd option must kill the script loudly. Codes cover start failures, contract violations, exceeded caps, provider and result faults, unserializable values, cancellation, and a consumer's classification of a run that settled with `stopReason: 'error'` (`RUN_FAILED`); the exact set and meanings live in [`src/index.ts`](src/index.ts). The per-item `null` is reserved for child-run failures and ordinary in-stage script errors, so a child that resolves normally with a non-completed stop reason is not an infrastructure exception: `agent()` returns `null`, letting the script handle an ordinary child failure. diff --git a/packages/workflow/workflow/README.zh.md b/packages/workflow/workflow/README.zh.md index 31c728a4f0..e6f1129263 100644 --- a/packages/workflow/workflow/README.zh.md +++ b/packages/workflow/workflow/README.zh.md @@ -86,7 +86,7 @@ return { reviewed: reviews.length } ### 失败纪律 -`WorkflowError` 携带机器可路由的 code 与 `fatal` 标志;每个 code 都是致命的,`parallel()` 与 `pipeline()` 会重新抛出致命错误,而不是把条目映射为 `null`——拼错的选项必须明确终止脚本。code 覆盖启动失败、约定违规、超出上限、提供方与结果故障、不可序列化值与取消;完整集合与含义见 [`src/index.ts`](src/index.ts)。 +`WorkflowError` 携带机器可路由的 code 与 `fatal` 标志;每个 code 都是致命的,`parallel()` 与 `pipeline()` 会重新抛出致命错误,而不是把条目映射为 `null`——拼错的选项必须明确终止脚本。code 覆盖启动失败、约定违规、超出上限、提供方与结果故障、不可序列化值、取消,以及消费方对以 `stopReason: 'error'` 结束的运行所作的分类(`RUN_FAILED`);完整集合与含义见 [`src/index.ts`](src/index.ts)。 逐项 `null` 只保留给子运行失败与阶段内普通脚本错误,因此以非完成结束原因正常结算的子 agent 不属于基础设施异常:`agent()` 返回 `null`,让脚本处理普通子 agent 失败。 diff --git a/packages/workflow/workflow/src/index.ts b/packages/workflow/workflow/src/index.ts index b78a972977..3d16d576be 100644 --- a/packages/workflow/workflow/src/index.ts +++ b/packages/workflow/workflow/src/index.ts @@ -102,8 +102,10 @@ export type WorkflowEventName = /** * Machine-routable fatal workflow failures: parse/meta/argument/schema errors, * resource caps, subagent infrastructure failures, unserializable boundary - * values, and cancellation. An ordinary child failure resolves its item to - * `null` and is not one of these fatal codes. + * values, and cancellation. `RUN_FAILED` is the consumer's classification of a + * run that settled with `stopReason: 'error'`, whose {@link WorkflowResult} + * carries only the failure message. An ordinary child failure resolves its item + * to `null` and is not one of these fatal codes. */ export type WorkflowErrorCode = | 'SCRIPT_PARSE' @@ -117,6 +119,7 @@ export type WorkflowErrorCode = | 'AGENT_RESULT' | 'RESULT_UNSERIALIZABLE' | 'CANCELLED' + | 'RUN_FAILED' /** * Typed error for workflow-seam failures. Extends {@link HarnessError}, so the From 5fe691f6e50c554a2db88a5af03bfc5998f00042 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:11:16 +0800 Subject: [PATCH 031/404] feat(team,goal,todo): code projection and argument failures A failed Team or goal projection now rejects with TeamError TEAM_STATE_CORRUPT or GoalError GOAL_STATE_CORRUPT, and GoalError assigns its name literally. team_task_list cursor, limit, and filter violations and todo_write content checks throw ToolArgsError; missing callers throw ToolContextUnavailableError. todo_write violation messages now name the offending item path. Refs #7869 --- packages/goal/goal/README.i18n.yaml | 4 ++-- packages/goal/goal/README.md | 2 +- packages/goal/goal/README.zh.md | 2 +- packages/goal/goal/src/domain.ts | 1 + packages/goal/goal/src/index.ts | 2 +- packages/goal/goal/src/runtime.ts | 3 +-- packages/goal/goal/tests/projection.spec.ts | 3 ++- packages/team/agent-team/README.i18n.yaml | 4 ++-- packages/team/agent-team/README.md | 2 +- packages/team/agent-team/README.zh.md | 2 +- packages/team/agent-team/src/journal.ts | 4 ++-- packages/team/agent-team/tests/team.spec.ts | 5 +++-- packages/team/tool-agent-team/src/index.ts | 10 +++++----- .../team/tool-agent-team/tests/tool-team.spec.ts | 6 +++--- packages/todo/tool-todo/README.i18n.yaml | 4 ++-- packages/todo/tool-todo/README.md | 2 +- packages/todo/tool-todo/README.zh.md | 2 +- packages/todo/tool-todo/src/index.ts | 12 ++++++------ .../todo/tool-todo/tests/loader-composition.spec.ts | 1 + packages/todo/tool-todo/tests/tool-todo.spec.ts | 3 +++ 20 files changed, 40 insertions(+), 34 deletions(-) diff --git a/packages/goal/goal/README.i18n.yaml b/packages/goal/goal/README.i18n.yaml index 4aa0d5c88d..8a267e47bb 100644 --- a/packages/goal/goal/README.i18n.yaml +++ b/packages/goal/goal/README.i18n.yaml @@ -39,8 +39,8 @@ en: 592af7e68423bd1c zh: 9b1f08393db1b14e /deepseek-ai-dsh-goal/understand-the-implementation/design: - en: 6f19e891ffc79754 - zh: 9599e3b142f1e6b5 + en: c14410306499e607 + zh: 99d1d91259127aba /deepseek-ai-dsh-goal/understand-the-implementation/source-map: en: aef62dff93f32796 zh: dba79da0466218a7 diff --git a/packages/goal/goal/README.md b/packages/goal/goal/README.md index 9e0a1ee60d..f7dea16728 100644 --- a/packages/goal/goal/README.md +++ b/packages/goal/goal/README.md @@ -98,7 +98,7 @@ This section explains how the service realizes the behavior above; the observabl - **Compare-and-set mutations.** `ctx.goals` accepts only the exact live `Agent` registered under its id. `get()` returns a detached `GoalView`; mutations take a `GoalRef { id, revision }` and reject stale refs. Creation resolves the deployment default internally before committing. - **Activation is process-local.** `armed` and `disarmed` live in a per-session cache and are never persisted. A fresh cache and every `agent/created` edge disarm continuation even when replay finds an active durable phase; `disarm()` removes authority without writing a revision or emitting a mutation. - **Strict replay.** The fold derives lifecycle mutations only from `goal/change` and rejects malformed shapes, discontinuous revisions, illegal phase transitions, non-monotonic per-goal timestamps, and non-sequential admitted rounds. Positive rounds advance only on admitted goal-sourced `user/message` events, and mutation timestamps clamp against the preceding update when wall time moves backward. -- **Projection unit.** The package requires the projection registry and registers a strict `goal` unit. Its host state retains replay validation data and the first failure, while its client view exposes the latest valid whole goal or `null`; `GoalService` rejects access after a retained replay failure. +- **Projection unit.** The package requires the projection registry and registers a strict `goal` unit. Its host state retains replay validation data and the first failure, while its client view exposes the latest valid whole goal or `null`; `GoalService` rejects access after a retained replay failure with `GoalError` `GOAL_STATE_CORRUPT`. ### Source map diff --git a/packages/goal/goal/README.zh.md b/packages/goal/goal/README.zh.md index ac8fd3837b..515c2e85e9 100644 --- a/packages/goal/goal/README.zh.md +++ b/packages/goal/goal/README.zh.md @@ -98,7 +98,7 @@ view.activation // 'armed' | 'disarmed' — not persisted - **比较并设置的变更。** `ctx.goals` 只接受以对应 id 注册的完全相同的活跃 `Agent` 实例。`get()` 返回脱离状态的 `GoalView`;变更携带 `GoalRef { id, revision }` 并拒绝陈旧引用。创建在提交前于内部解析部署默认值。 - **续行启用状态是进程本地的。** `armed` 与 `disarmed` 保存在每会话缓存中,绝不持久化。新缓存与每次 `agent/created` 边界都会停用续行,即使回放发现持久 phase 为 active;`disarm()` 移除续行权限,不写入 revision 也不发出变更事件。 - **严格回放。** 折叠只从 `goal/change` 派生生命周期变更,并拒绝形状错误、不连续 revision、非法 phase 转换、每目标时间戳非单调,以及不连续的已准入 Round。只有已准入的来源为 goal 的 `user/message` 事件会推进正数 Round;挂钟时间倒退时,变更时间戳会限制在不早于上一次更新的值。 -- **投影单元。** 本包要求提供投影注册表,并注册一个严格的 `goal` 单元。其宿主状态保留回放校验数据与第一次失败,客户端视图提供最新有效的完整 goal 或 `null`;保留回放失败后,`GoalService` 会拒绝访问。 +- **投影单元。** 本包要求提供投影注册表,并注册一个严格的 `goal` 单元。其宿主状态保留回放校验数据与第一次失败,客户端视图提供最新有效的完整 goal 或 `null`;保留回放失败后,`GoalService` 会以 `GoalError` `GOAL_STATE_CORRUPT` 拒绝访问。 ### 源码地图 diff --git a/packages/goal/goal/src/domain.ts b/packages/goal/goal/src/domain.ts index 63f1573dc7..68cba67262 100644 --- a/packages/goal/goal/src/domain.ts +++ b/packages/goal/goal/src/domain.ts @@ -100,6 +100,7 @@ export type GoalErrorCode = | 'GOAL_INVALID_BLOCK_REASON' | 'GOAL_INVALID_EDIT' | 'GOAL_INVALID_TRANSITION' + | 'GOAL_STATE_CORRUPT' declare module '@deepseek-ai/cordis' { interface Events { diff --git a/packages/goal/goal/src/index.ts b/packages/goal/goal/src/index.ts index 3d54ed75d6..a6530bf789 100644 --- a/packages/goal/goal/src/index.ts +++ b/packages/goal/goal/src/index.ts @@ -477,7 +477,7 @@ export class GoalService extends TypertRemoteService { /** Read the current durable projection maintained by the registry. */ private state(session: Session): GoalProjection | null { const state = this.goalProjectionHandle.stateOf(session) - if (state.failure !== null) throw new Error(state.failure) + if (state.failure !== null) throw new GoalError(state.failure, 'GOAL_STATE_CORRUPT') return state.current } diff --git a/packages/goal/goal/src/runtime.ts b/packages/goal/goal/src/runtime.ts index 2f5c40735a..b7b9ad4c6c 100644 --- a/packages/goal/goal/src/runtime.ts +++ b/packages/goal/goal/src/runtime.ts @@ -22,9 +22,8 @@ export class GoalError extends HarnessError { * @param message - human-readable rejection reason. * @param code - stable machine-routable classification. */ - // Keep the constructor to narrow HarnessError's string code at this boundary. - // oxlint-disable-next-line typescript/no-useless-constructor -- type-only narrowing constructor(message: string, code: GoalErrorCode) { super(message, code) + this.name = 'GoalError' } } diff --git a/packages/goal/goal/tests/projection.spec.ts b/packages/goal/goal/tests/projection.spec.ts index b2aa38622d..05b72eef6c 100644 --- a/packages/goal/goal/tests/projection.spec.ts +++ b/packages/goal/goal/tests/projection.spec.ts @@ -243,7 +243,8 @@ describe('goal projection unit', () => { await expect(agentEvents(bench.ctx, bench.agent).serial('agent/created', { source: 'resume' })) .resolves.toBeUndefined() - expect(() => bench.ctx.goals.get(bench.agent)).toThrow(failure) + expect(() => bench.ctx.goals.get(bench.agent)) + .toThrow(expect.objectContaining({ name: 'GoalError', code: 'GOAL_STATE_CORRUPT', message: failure })) expect(bench.tailValues().goal).toMatchObject({ goal: { objective: 'poisoned replay' } }) }) diff --git a/packages/team/agent-team/README.i18n.yaml b/packages/team/agent-team/README.i18n.yaml index 2f1733cd95..f8f298dda8 100644 --- a/packages/team/agent-team/README.i18n.yaml +++ b/packages/team/agent-team/README.i18n.yaml @@ -66,8 +66,8 @@ en: a8baf51f2fcd6d49 zh: 357c8db36823fe0e /deepseek-ai-dsh-agent-team/understand-the-implementation/browser-projection: - en: ed33e64ea55d2b75 - zh: eb326025ff156dea + en: 1f8e19f2c73b1cf5 + zh: 1e535d354ad47c08 /deepseek-ai-dsh-agent-team/further-exploration: en: 60d969ec526f5556 zh: ed4f813006f86215 diff --git a/packages/team/agent-team/README.md b/packages/team/agent-team/README.md index a58392c1c3..d5d6c2f507 100644 --- a/packages/team/agent-team/README.md +++ b/packages/team/agent-team/README.md @@ -147,7 +147,7 @@ Unloading the service unregisters the projection. The retained handle remains re ### Browser projection -The `agentTeam` projection publishes non-deleted task views and any failure beside the last valid state. Historical roster and mailbox records cannot cause a task-board projection failure. A failed projection rejects task reads and mutations without appending task events. Mode selections can still be saved and applied, including disabling Team; the projection failure remains visible. Invalid mode payloads retain the last valid selection and publish a projection failure. The [subsystem reference](../../../docs/subsystems/agent-team.md#web-projection) defines the wire types. +The `agentTeam` projection publishes non-deleted task views and any failure beside the last valid state. Historical roster and mailbox records cannot cause a task-board projection failure. A failed projection rejects task reads and mutations with `TeamError` `TEAM_STATE_CORRUPT` without appending task events. Mode selections can still be saved and applied, including disabling Team; the projection failure remains visible. Invalid mode payloads retain the last valid selection and publish a projection failure. The [subsystem reference](../../../docs/subsystems/agent-team.md#web-projection) defines the wire types. The [Web UI](../../client/ui-agent-team/README.md) displays tasks only. Ordinary subagent navigation owns the member list; task owner labels display the owner's full name, or its Session id when the owner has no name. diff --git a/packages/team/agent-team/README.zh.md b/packages/team/agent-team/README.zh.md index 9e57943fa1..204407b12d 100644 --- a/packages/team/agent-team/README.zh.md +++ b/packages/team/agent-team/README.zh.md @@ -147,7 +147,7 @@ Team 在激活前要求 `sessionPersistence` 可用。`Service.init` 等待 `age ### 浏览器投影 -`agentTeam` 投影发布未删除任务视图,并在最后有效状态旁报告失败。历史名册与邮箱记录不会导致任务板投影失败。投影失败后,任务读取和修改均报错,不再追加任务事件。模式选择仍可保存并生效,包括关闭 Team;投影错误持续可见。无效模式载荷保留最后有效选择,并发布投影错误。[子系统参考](../../../docs/subsystems/agent-team.zh.md#web-projection)定义线上的类型。 +`agentTeam` 投影发布未删除任务视图,并在最后有效状态旁报告失败。历史名册与邮箱记录不会导致任务板投影失败。投影失败后,任务读取和修改均以 `TeamError` `TEAM_STATE_CORRUPT` 报错,不再追加任务事件。模式选择仍可保存并生效,包括关闭 Team;投影错误持续可见。无效模式载荷保留最后有效选择,并发布投影错误。[子系统参考](../../../docs/subsystems/agent-team.zh.md#web-projection)定义线上的类型。 [Web UI](../../client/ui-agent-team/README.zh.md)仅展示任务。普通 subagent 导航负责成员列表;任务所有者标签显示所有者的完整名称,所有者没有名称时显示其 Session id。 diff --git a/packages/team/agent-team/src/journal.ts b/packages/team/agent-team/src/journal.ts index fd7c7fcfad..3e99c3b4d4 100644 --- a/packages/team/agent-team/src/journal.ts +++ b/packages/team/agent-team/src/journal.ts @@ -27,11 +27,11 @@ export class TeamJournal { * Read authoritative Team state for one exact live Lead. * @param root - exact live Team Lead. * @returns current projected state selected by the Lead Team id. - * @throws when the durable Team projection has failed. + * @throws {TeamError} `TEAM_STATE_CORRUPT` when the durable Team projection has failed. */ state(root: Agent): TeamState { const projection = this.teamProjectionHandle.stateOf(root.session) - if (projection.failure !== undefined) throw new Error(projection.failure) + if (projection.failure !== undefined) throw new TeamError(projection.failure, 'TEAM_STATE_CORRUPT') return projection } diff --git a/packages/team/agent-team/tests/team.spec.ts b/packages/team/agent-team/tests/team.spec.ts index f0724a9510..08d7d1e2c3 100644 --- a/packages/team/agent-team/tests/team.spec.ts +++ b/packages/team/agent-team/tests/team.spec.ts @@ -280,10 +280,11 @@ describe('Tree-owned task boards', () => { status: 'pending', blockedBy: [], writeScopes: [], }, }) - expect(() => ctx.agentTeams.listTasks(lead)).toThrow('must begin at revision 1') + const corrupt = { name: 'TeamError', code: 'TEAM_STATE_CORRUPT', message: expect.stringContaining('must begin at revision 1') as string } + expect(() => ctx.agentTeams.listTasks(lead)).toThrow(expect.objectContaining(corrupt)) const eventCount = lead.session.snapshotEvents().length await expect(ctx.agentTeams.createTask(lead, { subject: 'blocked', description: 'blocked' })) - .rejects.toThrow('must begin at revision 1') + .rejects.toMatchObject(corrupt) expect(lead.session.snapshotEvents()).toHaveLength(eventCount) }) diff --git a/packages/team/tool-agent-team/src/index.ts b/packages/team/tool-agent-team/src/index.ts index 353ad1c323..deaa07d572 100644 --- a/packages/team/tool-agent-team/src/index.ts +++ b/packages/team/tool-agent-team/src/index.ts @@ -6,7 +6,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import { SubagentError } from '@deepseek-ai/dsh-subagent' import { TeamTaskId } from '@deepseek-ai/dsh-agent-team' import type { TeamTaskView } from '@deepseek-ai/dsh-agent-team' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { InferValue, ValueSchemaSpec } from '@deepseek-ai/dsh-tools' /** Cordis plugin name. */ @@ -82,7 +82,7 @@ type NamedTaskView = Omit & { readonly ow /** Recover the exact caller guaranteed by conditional Team-tool discovery. */ function callingAgent(agent: Agent | undefined, toolName: string): Agent { /* v8 ignore next 2 -- The Team condition rejects callers without an Agent before execution. */ - if (agent === undefined) throw new Error(`${toolName} requires a calling Agent`) + if (agent === undefined) throw new ToolContextUnavailableError(`${toolName} requires a calling Agent`) return agent } @@ -159,10 +159,10 @@ export function apply(ctx: Context, config: Config = {}): void { async execute(args, exec) { const cursor = args.cursor ?? 0 const limit = args.limit ?? 50 - if (!Number.isSafeInteger(cursor) || cursor < 0) throw new Error('cursor must be a non-negative safe integer') - if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw new Error('limit must be an integer from 1 through 100') + if (!Number.isSafeInteger(cursor) || cursor < 0) throw new ToolArgsError(['cursor must be a non-negative safe integer']) + if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw new ToolArgsError(['limit must be an integer from 1 through 100']) const caller = callingAgent(exec.agent, 'team_task_list') - if (args.owner !== undefined && args.unowned !== undefined) throw new Error('owner and unowned filters cannot be combined') + if (args.owner !== undefined && args.unowned !== undefined) throw new ToolArgsError(['owner and unowned filters cannot be combined']) const owner = args.owner === undefined ? undefined : await ctx.subagents.resolveName(caller, args.owner, exec.signal) diff --git a/packages/team/tool-agent-team/tests/tool-team.spec.ts b/packages/team/tool-agent-team/tests/tool-team.spec.ts index db51194163..b286befd59 100644 --- a/packages/team/tool-agent-team/tests/tool-team.spec.ts +++ b/packages/team/tool-agent-team/tests/tool-team.spec.ts @@ -529,8 +529,8 @@ describe('dsh-tool-team', () => { expect(JSON.parse(text(await execute(ctx, lead, 'team_task_list', { cursor: 1, })))).not.toHaveProperty('nextCursor') - expect((await execute(ctx, lead, 'team_task_list', { cursor: -1 })).isError).toBe(true) - expect((await execute(ctx, lead, 'team_task_list', { limit: 101 })).isError).toBe(true) + expect(await execute(ctx, lead, 'team_task_list', { cursor: -1 })).toMatchObject({ isError: true, error: { info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } } }) + expect(await execute(ctx, lead, 'team_task_list', { limit: 101 })).toMatchObject({ isError: true, error: { info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } } }) const edited = await execute(ctx, lead, 'team_task_update', { task_id: first.id, @@ -588,7 +588,7 @@ describe('dsh-tool-team', () => { expect(JSON.parse(text(await execute(ctx, lead, 'team_task_list', { owner: 'unowned' })))).toMatchObject({ tasks: [{ id: assigned.id }] }) expect(JSON.parse(text(await execute(ctx, lead, 'team_task_list', { unowned: true })))).toMatchObject({ tasks: [{ id: pending.id }] }) expect(JSON.parse(text(await execute(ctx, lead, 'team_task_list', { unowned: false })))).toMatchObject({ tasks: [{ id: assigned.id }] }) - expect((await execute(ctx, lead, 'team_task_list', { owner: 'unowned', unowned: true })).isError).toBe(true) + expect(await execute(ctx, lead, 'team_task_list', { owner: 'unowned', unowned: true })).toMatchObject({ isError: true, error: { info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } } }) await child.dispose() }) diff --git a/packages/todo/tool-todo/README.i18n.yaml b/packages/todo/tool-todo/README.i18n.yaml index 2899c17810..4121828f2e 100644 --- a/packages/todo/tool-todo/README.i18n.yaml +++ b/packages/todo/tool-todo/README.i18n.yaml @@ -69,8 +69,8 @@ en: 9717b983b6a857e3 zh: 611a2dadf7c0c706 /deepseek-ai-dsh-tool-todo/model-experience/tool-call-history-and-result/what-the-model-sees: - en: 05644654d1bce8c6 - zh: ea2a42470fbb2ee1 + en: 98dbd1d31d6179af + zh: cd899d7c4ab9f2be /deepseek-ai-dsh-tool-todo/model-experience/tool-call-history-and-result/token-effect: en: 7763a0e875faf53d zh: fe33c3973215dc53 diff --git a/packages/todo/tool-todo/README.md b/packages/todo/tool-todo/README.md index 1c31e14ddd..d08b26801a 100644 --- a/packages/todo/tool-todo/README.md +++ b/packages/todo/tool-todo/README.md @@ -135,7 +135,7 @@ Prefix-stable while the definition and visibility are unchanged. Plugin lifecycl #### What the model sees -Each assistant tool call retains the entire replacement list in its arguments. Success returns exactly `Updated todo list: pending, in progress, completed.` Stable failures are ``Error: invalid todo: `content` must be a non-empty string``, `Error: invalid todos: duplicate content ""`, `Error: todo_write requires an owning agent session`, and — only where the deployment set `allowParallelInProgress: false` — `Error: invalid todos: at most one task may be in_progress (got )`. The full `todo/write` session event is UI and replay state, not a second model message. +Each assistant tool call retains the entire replacement list in its arguments. Success returns exactly `Updated todo list: pending, in progress, completed.` Stable failures are `Error: invalid arguments: todos[].content must be a non-empty string`, `Error: invalid arguments: todos[].content duplicates ""`, and — only where the deployment set `allowParallelInProgress: false` — `Error: invalid arguments: at most one task may be in_progress (got )`, all `ToolArgsError` `INVALID_ARGS`, plus `Error: todo_write requires an owning agent session` as `ToolContextUnavailableError` `TOOL_CONTEXT_UNAVAILABLE`. The full `todo/write` session event is UI and replay state, not a second model message. #### Token effect diff --git a/packages/todo/tool-todo/README.zh.md b/packages/todo/tool-todo/README.zh.md index 6ceae4cc3e..10ffd2f05f 100644 --- a/packages/todo/tool-todo/README.zh.md +++ b/packages/todo/tool-todo/README.zh.md @@ -135,7 +135,7 @@ agent 每次更新都发送完整列表;新列表替换旧列表,因此没 #### 模型看到什么 -每次 assistant 工具调用都会在参数中保留整个替换列表。成功时原样返回 `Updated todo list: pending, in progress, completed.`。稳定失败文本为 ``Error: invalid todo: `content` must be a non-empty string``、`Error: invalid todos: duplicate content ""`、`Error: todo_write requires an owning agent session`,以及——仅在部署设置 `allowParallelInProgress: false` 时——`Error: invalid todos: at most one task may be in_progress (got )`。完整的 `todo/write` 会话事件是 UI 与回放状态,而非第二条模型消息。 +每次 assistant 工具调用都会在参数中保留整个替换列表。成功时原样返回 `Updated todo list: pending, in progress, completed.`。稳定失败文本为 `Error: invalid arguments: todos[].content must be a non-empty string`、`Error: invalid arguments: todos[].content duplicates ""`,以及——仅在部署设置 `allowParallelInProgress: false` 时——`Error: invalid arguments: at most one task may be in_progress (got )`,均为 `ToolArgsError` `INVALID_ARGS`;另有 `ToolContextUnavailableError` `TOOL_CONTEXT_UNAVAILABLE` 的 `Error: todo_write requires an owning agent session`。完整的 `todo/write` 会话事件是 UI 与回放状态,而非第二条模型消息。 #### Token 影响 diff --git a/packages/todo/tool-todo/src/index.ts b/packages/todo/tool-todo/src/index.ts index 0f59f7be17..53ac76ac86 100644 --- a/packages/todo/tool-todo/src/index.ts +++ b/packages/todo/tool-todo/src/index.ts @@ -9,7 +9,7 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { z as zod } from 'zod' import type { ZodType } from 'zod' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { TodoItem } from './types.ts' // Type-only: resolves the required ctx.sessionProjections service declaration. import type {} from '@deepseek-ai/dsh-session-projection' @@ -81,20 +81,20 @@ function toTodoList(raw: { content: string; status: string }[], allowParallel: b const todos: TodoItem[] = [] const seen = new Set() let active = 0 - for (const item of raw) { + for (const [index, item] of raw.entries()) { const content = item.content.trim() if (content.length === 0) { - throw new Error('invalid todo: `content` must be a non-empty string') + throw new ToolArgsError([`todos[${index}].content must be a non-empty string`]) } if (seen.has(content)) { - throw new Error(`invalid todos: duplicate content ${JSON.stringify(content)}`) + throw new ToolArgsError([`todos[${index}].content duplicates ${JSON.stringify(content)}`]) } seen.add(content) if (item.status === 'in_progress') active++ todos.push({ content, status: item.status as TodoItem['status'] }) } if (!allowParallel && active > 1) { - throw new Error(`invalid todos: at most one task may be in_progress (got ${active})`) + throw new ToolArgsError([`at most one task may be in_progress (got ${active})`]) } return todos } @@ -195,7 +195,7 @@ export async function apply(ctx: Context, config: Config): Promise { if (!exec.agent) { // The list is per-agent-session state; a non-agent caller (no owning // session) has nowhere to write it. Reject rather than silently no-op. - throw new Error('todo_write requires an owning agent session') + throw new ToolContextUnavailableError('todo_write requires an owning agent session') } exec.agent.session.append('todo/write', { todos }) const count = (status: TodoItem['status']): number => todos.filter(t => t.status === status).length diff --git a/packages/todo/tool-todo/tests/loader-composition.spec.ts b/packages/todo/tool-todo/tests/loader-composition.spec.ts index e6f39365b9..584d40c200 100644 --- a/packages/todo/tool-todo/tests/loader-composition.spec.ts +++ b/packages/todo/tool-todo/tests/loader-composition.spec.ts @@ -118,6 +118,7 @@ describe('tool-todo real Loader composition through cordis.yml', () => { }) expect(result.isError).toBe(true) expect(resultText(result)).toContain('at most one task may be in_progress') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) expect(owner.session.snapshotEvents().some(e => e.type === 'todo/write')).toBe(false) }, 30_000) diff --git a/packages/todo/tool-todo/tests/tool-todo.spec.ts b/packages/todo/tool-todo/tests/tool-todo.spec.ts index 1c8f49e221..01bfc8c638 100644 --- a/packages/todo/tool-todo/tests/tool-todo.spec.ts +++ b/packages/todo/tool-todo/tests/tool-todo.spec.ts @@ -157,6 +157,7 @@ describe('dsh-tool-todo', () => { const result = await callTodo(ctx, { todos: parallel }, { agent }) expect(result.isError).toBe(true) expect(text(result)).toContain('at most one task may be in_progress') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) // A rejected call must not reach the durable log. expect(agent.session.snapshotEvents().some(e => e.type === 'todo/write')).toBe(false) }) @@ -198,6 +199,7 @@ describe('dsh-tool-todo', () => { const result = await callTodo(ctx, { todos }) expect(result.isError).toBe(true) expect(text(result)).toContain(fragment) + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) }) it('rejects a non-agent caller (the list has no owning session)', async () => { @@ -205,6 +207,7 @@ describe('dsh-tool-todo', () => { const result = await callTodo(ctx, { todos: [{ content: 'a', status: 'pending' }] }, { agent: undefined }) expect(result.isError).toBe(true) expect(text(result)).toContain('owning agent session') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it('presents the call with a stable title and the list as raw input', async () => { From 5157e3205a8d7bb05387b5abfe6c1250ba9ee777 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:11:17 +0800 Subject: [PATCH 032/404] feat(user-questions): classify answerer failures and timed ask checks An answerer failure that is not a HarnessError now rejects with UserQuestionError PROVIDER_ERROR and keeps the original as cause, while a coded HarnessError keeps its name and code. The timed ask_user_question tool reports an invalid timeout as BAD_TIMEOUT, a repeated question id as the new DUPLICATE_QUESTION_ID, and a missing caller as CALLER_NOT_LIVE. Refs #7869 --- docs/subsystems/user-questions.i18n.yaml | 4 ++-- docs/subsystems/user-questions.md | 8 ++++--- docs/subsystems/user-questions.zh.md | 8 ++++--- .../extensions/tool-cordis/src/api-catalog.ts | 2 +- .../tool-ask-user/README.i18n.yaml | 4 ++-- packages/interaction/tool-ask-user/README.md | 2 +- .../interaction/tool-ask-user/README.zh.md | 2 +- .../interaction/tool-ask-user/src/timed.ts | 10 +++++---- .../tool-ask-user/tests/tool-ask-user.spec.ts | 10 ++++++++- .../interaction/user-questions/src/index.ts | 9 +++++--- .../tests/user-questions.spec.ts | 21 +++++++++++-------- 11 files changed, 50 insertions(+), 30 deletions(-) diff --git a/docs/subsystems/user-questions.i18n.yaml b/docs/subsystems/user-questions.i18n.yaml index 808a19468f..bacd251ef1 100644 --- a/docs/subsystems/user-questions.i18n.yaml +++ b/docs/subsystems/user-questions.i18n.yaml @@ -24,5 +24,5 @@ en: 74fa698d4a115e80 zh: 4e9b03b5eab2ae5e /user-interaction/errors: - en: 5762b1498a426ab6 - zh: bb9987ec82103620 + en: eb0a4f94282f8c18 + zh: 92c41869431b120e diff --git a/docs/subsystems/user-questions.md b/docs/subsystems/user-questions.md index 2c86b22e1c..c87fe49f14 100644 --- a/docs/subsystems/user-questions.md +++ b/docs/subsystems/user-questions.md @@ -209,7 +209,7 @@ After a Host restart, the Remote layer resumes the root agent when the Session r ## Errors -`UserQuestionError` extends `HarnessError`, so `ctx.tools.execute()` preserves `{ name, code }` for model-facing tool failures such as `EMPTY_QUESTIONS`, `BAD_INTENT`, `NO_PROVIDER`, `ASK_ABORTED`, or UI-side cancellation. +`UserQuestionError` extends `HarnessError`, so `ctx.tools.execute()` preserves `{ name, code }` for model-facing tool failures such as `EMPTY_QUESTIONS`, `BAD_INTENT`, `NO_PROVIDER`, `ASK_ABORTED`, or UI-side cancellation. An answerer failure that is not a `HarnessError` becomes `PROVIDER_ERROR` with the original as `cause`; another `HarnessError` keeps its own `name` and `code`. ```ts type-equiv /** Stable error taxonomy for user-questions failures. */ @@ -286,8 +286,10 @@ async askTimed( request: AskUserQuestionRequest & { agent: Agent }, callId: Tool * @returns The answer chosen or typed by the human. * @throws {UserQuestionError} code `ASK_ABORTED` when the supplied signal * is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent - * is not the registry's exact live instance, or `DELEGATED_CALLER` when - * that live agent has subagent origin. + * is not the registry's exact live instance, `DELEGATED_CALLER` when + * that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer + * fails with a value that is not a `HarnessError`; a coded `HarnessError` + * from an answerer keeps its `name` and `code`. */ async ask(request: AskUserQuestionRequest): Promise ``` diff --git a/docs/subsystems/user-questions.zh.md b/docs/subsystems/user-questions.zh.md index ad39e1004f..4dc465f750 100644 --- a/docs/subsystems/user-questions.zh.md +++ b/docs/subsystems/user-questions.zh.md @@ -209,7 +209,7 @@ Host 重启后,Session 重开时 Remote 层会恢复根 agent。之后的迟 ## 错误 -`UserQuestionError` 继承 `HarnessError`,因此 `ctx.tools.execute()` 会保留 `{ name, code }`,用于面向模型的工具失败,如 `EMPTY_QUESTIONS`、`BAD_INTENT`、`NO_PROVIDER`、`ASK_ABORTED` 或 UI 侧取消。 +`UserQuestionError` 继承 `HarnessError`,因此 `ctx.tools.execute()` 会保留 `{ name, code }`,用于面向模型的工具失败,如 `EMPTY_QUESTIONS`、`BAD_INTENT`、`NO_PROVIDER`、`ASK_ABORTED` 或 UI 侧取消。不是 `HarnessError` 的应答方失败会变为 `PROVIDER_ERROR`,原错误作为 `cause`;其他 `HarnessError` 保留自身的 `name` 与 `code`。 ```ts type-equiv /** Stable error taxonomy for user-questions failures. */ @@ -286,8 +286,10 @@ async askTimed( request: AskUserQuestionRequest & { agent: Agent }, callId: Tool * @returns The answer chosen or typed by the human. * @throws {UserQuestionError} code `ASK_ABORTED` when the supplied signal * is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent - * is not the registry's exact live instance, or `DELEGATED_CALLER` when - * that live agent has subagent origin. + * is not the registry's exact live instance, `DELEGATED_CALLER` when + * that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer + * fails with a value that is not a `HarnessError`; a coded `HarnessError` + * from an answerer keeps its `name` and `code`. */ async ask(request: AskUserQuestionRequest): Promise ``` diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 74a5703129..199ff2c9a5 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -4369,7 +4369,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ description: 'Ask the scoped answerer waterfall and wait for the user\'s answer.\n\nWhen a caller supplies an agent, human interaction is valid only for the exact live instance of an ordinary Session. Explicit subagent origin rejects delegated callers; historical ordinary forks may retain parent metadata and still ask normally.', parameters: [{ name: 'request', description: 'Questions, owner agent, and abort signal.' }], returns: 'The answer chosen or typed by the human.', - throws: ['{UserQuestionError} code `ASK_ABORTED` when the supplied signal is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent is not the registry\'s exact live instance, or `DELEGATED_CALLER` when that live agent has subagent origin.'], + throws: ['{UserQuestionError} code `ASK_ABORTED` when the supplied signal is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent is not the registry\'s exact live instance, `DELEGATED_CALLER` when that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer fails with a value that is not a `HarnessError`; a coded `HarnessError` from an answerer keeps its `name` and `code`.'], }, ], }, diff --git a/packages/interaction/tool-ask-user/README.i18n.yaml b/packages/interaction/tool-ask-user/README.i18n.yaml index c065b0c79d..6bf59ccd8a 100644 --- a/packages/interaction/tool-ask-user/README.i18n.yaml +++ b/packages/interaction/tool-ask-user/README.i18n.yaml @@ -24,8 +24,8 @@ en: 3e4bc86d1d86eaab zh: 3c4c41666135f55d /deepseek-ai-dsh-tool-ask-user/use-this-package/when-the-call-fails: - en: c4ac3c584f900230 - zh: bd8d227f0637b8f1 + en: f18fe6f907ad9fe8 + zh: 5ea600e24c781522 /deepseek-ai-dsh-tool-ask-user/understand-the-implementation: en: e9b9d46be0b45ca2 zh: c02403486473cd80 diff --git a/packages/interaction/tool-ask-user/README.md b/packages/interaction/tool-ask-user/README.md index c479ab53ff..f2f4b18d90 100644 --- a/packages/interaction/tool-ask-user/README.md +++ b/packages/interaction/tool-ask-user/README.md @@ -71,7 +71,7 @@ For a finite timed call, `{ "pending": true, "callId": "…" }` means the foregr ### When the call fails -Legacy and `timeout: -1` calls wait for an answer or cancellation; without an accepting answerer, they return an error. A finite timed call without an answerer returns pending at its deadline. Cancellation and a caller that is not the exact live runtime root also return errors. A live child agent is rejected with `DELEGATED_CALLER` and must include the unresolved decision in its final result. +Legacy and `timeout: -1` calls wait for an answer or cancellation; without an accepting answerer, they return an error. A finite timed call without an answerer returns pending at its deadline. Cancellation and a caller that is not the exact live runtime root also return errors. A timed call rejects an out-of-range `timeout` with `BAD_TIMEOUT`, a repeated question id with `DUPLICATE_QUESTION_ID`, and a missing calling agent with `CALLER_NOT_LIVE`, all as `UserQuestionError`. A live child agent is rejected with `DELEGATED_CALLER` and must include the unresolved decision in its final result. ----- diff --git a/packages/interaction/tool-ask-user/README.zh.md b/packages/interaction/tool-ask-user/README.zh.md index 8c577cb40d..1f76d6ab68 100644 --- a/packages/interaction/tool-ask-user/README.zh.md +++ b/packages/interaction/tool-ask-user/README.zh.md @@ -71,7 +71,7 @@ kind: "package-reference" ### 调用何时失败 -Legacy 调用和 `timeout: -1` 调用会等待回答或取消;没有 answerer 接受时返回错误。有限时长的 timed 调用若没有 answerer,则在到期后返回 pending。取消调用,或调用方不是确切的存活运行时根时,也会返回错误。存活的子 agent 会以 `DELEGATED_CALLER` 被拒绝,必须在最终结果中包含尚未解决的决定。 +Legacy 调用和 `timeout: -1` 调用会等待回答或取消;没有 answerer 接受时返回错误。有限时长的 timed 调用若没有 answerer,则在到期后返回 pending。取消调用,或调用方不是确切的存活运行时根时,也会返回错误。timed 调用会以 `BAD_TIMEOUT` 拒绝超出范围的 `timeout`,以 `DUPLICATE_QUESTION_ID` 拒绝重复的问题 id,以 `CALLER_NOT_LIVE` 拒绝缺少调用方 agent 的调用,均为 `UserQuestionError`。存活的子 agent 会以 `DELEGATED_CALLER` 被拒绝,必须在最终结果中包含尚未解决的决定。 ----- diff --git a/packages/interaction/tool-ask-user/src/timed.ts b/packages/interaction/tool-ask-user/src/timed.ts index 9f3260ddcd..c5f3c5c1a8 100644 --- a/packages/interaction/tool-ask-user/src/timed.ts +++ b/packages/interaction/tool-ask-user/src/timed.ts @@ -4,14 +4,14 @@ import type { Context } from '@deepseek-ai/cordis' import { defineTool, type ToolExecution } from '@deepseek-ai/dsh-tools' -import { TIMED_WAIT_PARAMETER } from '@deepseek-ai/dsh-user-questions' +import { TIMED_WAIT_PARAMETER, UserQuestionError } from '@deepseek-ai/dsh-user-questions' import type { AskUserQuestionAnswer, AskUserQuestionRequestEvent, } from '@deepseek-ai/dsh-user-questions/types' function validateTimeout(timeout: number): number { if (timeout !== -1 && (!Number.isInteger(timeout) || timeout < 1 || timeout > 2_147_483)) { - throw new Error('timeout must be -1 or a positive integer up to 2147483 seconds') + throw new UserQuestionError('timeout must be -1 or a positive integer up to 2147483 seconds', 'BAD_TIMEOUT') } return timeout } @@ -19,7 +19,9 @@ function validateTimeout(timeout: number): number { function validateQuestionIds(questions: readonly { readonly id: string }[]): void { const ids = new Set() for (const question of questions) { - if (ids.has(question.id)) throw new Error(`question id ${JSON.stringify(question.id)} must be unique within this call`) + if (ids.has(question.id)) { + throw new UserQuestionError(`question id ${JSON.stringify(question.id)} must be unique within this call`, 'DUPLICATE_QUESTION_ID') + } ids.add(question.id) } } @@ -197,7 +199,7 @@ export function registerTimedAskUser(ctx: Context, timeout = 120): void { validateQuestionIds(args.questions) const request = questionRequest(args.questions, exec) if (timeout !== -1) { - if (exec.agent === undefined) throw new Error('timed questions require a live agent') + if (exec.agent === undefined) throw new UserQuestionError('timed questions require a live agent', 'CALLER_NOT_LIVE') const result = await ctx.userQuestions.askTimed({ ...request, agent: exec.agent }, exec.callId, timeout * 1000) return 'pending' in result ? { ...result, message: pendingNotice } : answerResult(result) } diff --git a/packages/interaction/tool-ask-user/tests/tool-ask-user.spec.ts b/packages/interaction/tool-ask-user/tests/tool-ask-user.spec.ts index 122b03023b..30e2c4629f 100644 --- a/packages/interaction/tool-ask-user/tests/tool-ask-user.spec.ts +++ b/packages/interaction/tool-ask-user/tests/tool-ask-user.spec.ts @@ -554,10 +554,16 @@ describe('ask_user_question tool', () => { expect(result).toMatchObject({ isError: true, content: [{ type: 'text', text: 'Error: timed questions require a live agent' }], + error: { info: { name: 'UserQuestionError', code: 'CALLER_NOT_LIVE' } }, }) }) - it.each([0, 1.5, 2_147_484])('rejects invalid timeout %s', async (timeout) => { + it.each([ + // The integer schema rejects a fraction before the tool body's range check. + { timeout: 0, info: { name: 'UserQuestionError', code: 'BAD_TIMEOUT' } }, + { timeout: 1.5, info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } }, + { timeout: 2_147_484, info: { name: 'UserQuestionError', code: 'BAD_TIMEOUT' } }, + ])('rejects invalid timeout $timeout', async ({ timeout, info }) => { const ctx = await setup({ mode: 'timed', timeout: -1 }) const result = await executeToolFixture(ctx, { @@ -570,6 +576,7 @@ describe('ask_user_question tool', () => { expect(result.isError).toBe(true) expect(result.content[0]).toMatchObject({ type: 'text' }) expect(result.content[0]?.type === 'text' ? result.content[0].text : '').toMatch(/timeout.*integer/i) + expect(result.error?.info).toEqual(info) }) it('rejects duplicate question ids before dispatching a timed call', async () => { @@ -590,6 +597,7 @@ describe('ask_user_question tool', () => { expect(result).toMatchObject({ isError: true, content: [{ type: 'text', text: 'Error: question id "scope" must be unique within this call' }], + error: { info: { name: 'UserQuestionError', code: 'DUPLICATE_QUESTION_ID' } }, }) expect(answerer).not.toHaveBeenCalled() }) diff --git a/packages/interaction/user-questions/src/index.ts b/packages/interaction/user-questions/src/index.ts index 2804b9ca30..0242301291 100644 --- a/packages/interaction/user-questions/src/index.ts +++ b/packages/interaction/user-questions/src/index.ts @@ -285,8 +285,10 @@ export class UserQuestionService extends TypertRemoteService { * @returns The answer chosen or typed by the human. * @throws {UserQuestionError} code `ASK_ABORTED` when the supplied signal * is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent - * is not the registry's exact live instance, or `DELEGATED_CALLER` when - * that live agent has subagent origin. + * is not the registry's exact live instance, `DELEGATED_CALLER` when + * that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer + * fails with a value that is not a `HarnessError`; a coded `HarnessError` + * from an answerer keeps its `name` and `code`. */ async ask(request: AskUserQuestionRequest): Promise { if (request.signal?.aborted) { @@ -356,7 +358,8 @@ export class UserQuestionService extends TypertRemoteService { if (request.signal?.aborted) { throw abortedQuestion(error) } - throw restored + if (restored instanceof HarnessError) throw restored + throw new UserQuestionError('the user-questions answerer failed before the user answered', 'PROVIDER_ERROR', { cause: error }) } } } diff --git a/packages/interaction/user-questions/tests/user-questions.spec.ts b/packages/interaction/user-questions/tests/user-questions.spec.ts index b2097ba376..d76ade47db 100644 --- a/packages/interaction/user-questions/tests/user-questions.spec.ts +++ b/packages/interaction/user-questions/tests/user-questions.spec.ts @@ -7,7 +7,7 @@ import UserQuestionService, { type AskUserQuestionAnswer, type AskUserQuestionRequest, } from '@deepseek-ai/dsh-user-questions' -import { createToolResultMessage, createUserMessage, ToolCallId, type ToolSchema, type UserMessage } from '@deepseek-ai/dsh-llm' +import { createToolResultMessage, createUserMessage, HarnessError, ToolCallId, type ToolSchema, type UserMessage } from '@deepseek-ai/dsh-llm' import { Session, SessionId, SESSION_FORMAT_VERSION, TOOL_OUTCOME_UNKNOWN } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' @@ -178,14 +178,16 @@ describe('UserQuestionService', () => { name: 'UserQuestionError', })], ['a non-Error rejection', { name: 'UserQuestionError', code: 'ASK_CANCELLED' }], - ])('preserves %s from the provider', async (_label, rejection) => { + ])('classifies %s from the provider as PROVIDER_ERROR', async (_label, rejection) => { const ctx = new Context() await ctx.plugin(UserQuestionService) registerAnswerer(ctx, { ask: vi.fn().mockRejectedValue(rejection) }) - await expect(ctx.userQuestions.ask({ + const failure = await ctx.userQuestions.ask({ questions: [{ id: 'confirm', question: 'Proceed?' }], - })).rejects.toBe(rejection) + }).then(() => undefined, (error: unknown) => error) + expect(failure).toBeInstanceOf(UserQuestionError) + expect(failure).toMatchObject({ name: 'UserQuestionError', code: 'PROVIDER_ERROR', cause: rejection }) }) it('rejects empty question batches before reaching the provider', async () => { @@ -289,10 +291,10 @@ describe('UserQuestionService', () => { }) }) - it('preserves a provider rejection outside the UserQuestionError taxonomy', async () => { + it('preserves a coded provider rejection outside the UserQuestionError taxonomy', async () => { const ctx = new Context() await ctx.plugin(UserQuestionService) - const failure = new Error('provider failed') + const failure = new HarnessError('provider failed', 'PROVIDER_OFFLINE') registerAnswerer(ctx, { ask: () => Promise.reject(failure) }) await expect(ctx.userQuestions.ask({ @@ -568,14 +570,15 @@ describe('askTimed', () => { } }) - it('rethrows a provider failure that is not a question error', async () => { + it('classifies a provider failure that is not a question error as PROVIDER_ERROR', async () => { const ctx = await timedContext() const agent = liveAgent('timed-provider-crash') ctx.agents.enter(agent) - registerAnswerer(ctx, { ask: () => Promise.reject(new TypeError('provider crashed')) }) + const crash = new TypeError('provider crashed') + registerAnswerer(ctx, { ask: () => Promise.reject(crash) }) await expect(ctx.userQuestions.askTimed({ agent, questions: timedQuestions }, timedCallId, 120_000)) - .rejects.toThrow(TypeError) + .rejects.toMatchObject({ name: 'UserQuestionError', code: 'PROVIDER_ERROR', cause: crash }) await ctx.fiber.dispose() }) From a2e31ad6f958f477d3a1073cfb068f3d9b201305 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:11:25 +0800 Subject: [PATCH 033/404] docs: regenerate catalogs for shifted source lines The config, persistence, and event producer-consumer catalogs record source line numbers that moved in the preceding error-code changes; no persisted type digest changed. Refs #7869 --- docs/config-catalog.md | 6 +++--- docs/config-catalog.zh.md | 6 +++--- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- docs/persistence-catalog.i18n.yaml | 12 ++++++------ docs/persistence-catalog.md | 6 +++--- docs/persistence-catalog.zh.md | 6 +++--- docs/persistence-schema.json | 4 ++-- 8 files changed, 22 insertions(+), 22 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 7562c8bf96..a0eb5198ce 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -2670,7 +2670,7 @@ export interface Config { ## `@deepseek-ai/dsh-plan-mode` - `inject`: `tools` · `systemPrompt` · `sessionProjections` · `agents` -- `source`: [`packages/plan/plan-mode/src/index.ts:67`](../packages/plan/plan-mode/src/index.ts) +- `source`: [`packages/plan/plan-mode/src/index.ts:69`](../packages/plan/plan-mode/src/index.ts) ```ts config-catalog /** Deployment-owned plan guidance. */ @@ -4480,7 +4480,7 @@ export interface Config { - `inject`: `tools` · `subagents` · `systemPrompt` · `sessionProjections` - `refs`: [`AgentOptions`](subsystems/core.md) -- `source`: [`packages/subagent/tool-subagent/src/index.ts:45`](../packages/subagent/tool-subagent/src/index.ts) +- `source`: [`packages/subagent/tool-subagent/src/index.ts:46`](../packages/subagent/tool-subagent/src/index.ts) ```ts config-catalog /** Config: which registered provider this tool delegates to, plus child defaults. */ @@ -4627,7 +4627,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-workflow` - `inject`: `tools` · `workflowEngine` · `systemPrompt` -- `source`: [`packages/workflow/tool-workflow/src/index.ts:44`](../packages/workflow/tool-workflow/src/index.ts) +- `source`: [`packages/workflow/tool-workflow/src/index.ts:45`](../packages/workflow/tool-workflow/src/index.ts) ```ts config-catalog /** Config: the model-facing tool name plus result rendering caps. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 0d75b6e523..3d137345e3 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -2672,7 +2672,7 @@ export interface Config { ## `@deepseek-ai/dsh-plan-mode` - `inject`: `tools` · `systemPrompt` · `sessionProjections` · `agents` -- `source`: [`packages/plan/plan-mode/src/index.ts:67`](../packages/plan/plan-mode/src/index.ts) +- `source`: [`packages/plan/plan-mode/src/index.ts:69`](../packages/plan/plan-mode/src/index.ts) ```ts config-catalog /** Deployment-owned plan guidance. */ @@ -4482,7 +4482,7 @@ export interface Config { - `inject`: `tools` · `subagents` · `systemPrompt` · `sessionProjections` - `refs`: [`AgentOptions`](subsystems/core.zh.md) -- `source`: [`packages/subagent/tool-subagent/src/index.ts:45`](../packages/subagent/tool-subagent/src/index.ts) +- `source`: [`packages/subagent/tool-subagent/src/index.ts:46`](../packages/subagent/tool-subagent/src/index.ts) ```ts config-catalog /** Config: which registered provider this tool delegates to, plus child defaults. */ @@ -4629,7 +4629,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-workflow` - `inject`: `tools` · `workflowEngine` · `systemPrompt` -- `source`: [`packages/workflow/tool-workflow/src/index.ts:44`](../packages/workflow/tool-workflow/src/index.ts) +- `source`: [`packages/workflow/tool-workflow/src/index.ts:45`](../packages/workflow/tool-workflow/src/index.ts) ```ts config-catalog /** Config: the model-facing tool name plus result rendering caps. */ diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 7e1a837be5..b610bfb030 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -53,7 +53,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:92`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` | | `fs/write-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:66`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `goal/activation-changed` | `emit` | [`packages/goal/goal/src/types.ts:147`](../packages/goal/goal/src/types.ts) | [`goal`](../packages/goal/goal) (`emit`) | `remotes`, `server` | -| `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:114`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | +| `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:115`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | | `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:35`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | | `hmr/reload` | `emit` | [`packages/boot/hmr/src/index.ts:40`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | | `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:114`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 85f0623eaf..2d3999762a 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -55,7 +55,7 @@ | `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:92`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` | | `fs/write-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:66`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `goal/activation-changed` | `emit` | [`packages/goal/goal/src/types.ts:147`](../packages/goal/goal/src/types.ts) | [`goal`](../packages/goal/goal) (`emit`) | `remotes`, `server` | -| `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:114`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | +| `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:115`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | | `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:35`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | | `hmr/reload` | `emit` | [`packages/boot/hmr/src/index.ts:40`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | | `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:114`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index a5fb682b48..6929a9f050 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -153,8 +153,8 @@ en: 4294f78d26ed985b zh: 4294f78d26ed985b /session-persistence-event-catalog/events/plan/plan-mode-log-only: - en: 9ae5537eeae238de - zh: 6be761c7fd83fdce + en: bcc1f048e7a31f1e + zh: a9c29711722cd6c7 /session-persistence-event-catalog/events/request: en: a8df82440ebdf5f8 zh: a8df82440ebdf5f8 @@ -1227,8 +1227,8 @@ en: b45c7e8370d7be1e zh: 252fdc0ff2b9338c /session-persistence-event-catalog/resolved-persistence-types/sessiontitlemodelidentity: - en: 9531468264499498 - zh: 9da23c0ad2776563 + en: 9815df505b8cd026 + zh: ce4f536eec979d77 /session-persistence-event-catalog/resolved-persistence-types/sessiontitlemodelidentity~2: en: 13de8e35b749db45 zh: 01e4f3bcb6784fc8 @@ -1425,8 +1425,8 @@ en: a74e3dfa51c987af zh: 6c3c87974d7a7260 /session-persistence-event-catalog/resolved-persistence-types/active~2: - en: c861888d6239b700 - zh: a9b2271d3c6b8737 + en: 235f08eeb284a1a5 + zh: b6ebffbfd7b44a9b /session-persistence-event-catalog/resolved-persistence-types/agentpreset: en: 1282a0b3d5fa8d4d zh: aa533aea643dbefb diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 6b80fbbc99..d75f7f9558 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -735,7 +735,7 @@ Source: [`packages/interaction/permission-presets/src/index.ts:53`](../packages/ 'plan/mode': { active: boolean } ``` -Source: [`packages/plan/plan-mode/src/index.ts:53`](../packages/plan/plan-mode/src/index.ts) +Source: [`packages/plan/plan-mode/src/index.ts:55`](../packages/plan/plan-mode/src/index.ts) ### `request/*` @@ -4779,7 +4779,7 @@ Sources: [`packages/session/session-title-llm/src/index.ts:43`](../packages/sess SHA-256: `07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235` -Sources: [`packages/session/session-title/src/types.ts:20`](../packages/session/session-title/src/types.ts) · [`packages/subagent/tool-subagent/src/model-selection.ts:9`](../packages/subagent/tool-subagent/src/model-selection.ts) +Sources: [`packages/session/session-title/src/types.ts:20`](../packages/session/session-title/src/types.ts) · [`packages/subagent/tool-subagent/src/model-selection.ts:11`](../packages/subagent/tool-subagent/src/model-selection.ts) | Property | Presence | Type | |---|---|---| @@ -5870,7 +5870,7 @@ Array of `unknown` (opaque). SHA-256: `20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5` -Sources: [`packages/plan/plan-mode/src/index.ts:53`](../packages/plan/plan-mode/src/index.ts) +Sources: [`packages/plan/plan-mode/src/index.ts:55`](../packages/plan/plan-mode/src/index.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index c73b594c28..df1efe0f1e 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -737,7 +737,7 @@ export type SessionEvent = { 'plan/mode': { active: boolean } ``` -来源:[`packages/plan/plan-mode/src/index.ts:53`](../packages/plan/plan-mode/src/index.ts) +来源:[`packages/plan/plan-mode/src/index.ts:55`](../packages/plan/plan-mode/src/index.ts) ### `request/*` @@ -4781,7 +4781,7 @@ SHA-256: `bec5ca3a376f56f3d69df7f12a48e1cc07d4ea8305968773394c8734799faeb4` SHA-256: `07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235` -来源:[`packages/session/session-title/src/types.ts:20`](../packages/session/session-title/src/types.ts) · [`packages/subagent/tool-subagent/src/model-selection.ts:9`](../packages/subagent/tool-subagent/src/model-selection.ts) +来源:[`packages/session/session-title/src/types.ts:20`](../packages/session/session-title/src/types.ts) · [`packages/subagent/tool-subagent/src/model-selection.ts:11`](../packages/subagent/tool-subagent/src/model-selection.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -5872,7 +5872,7 @@ SHA-256: `b1664fa89f8eab49a14e7e3168d8bc4da4aa9fd76332f6c4a053d839e5276ae7` SHA-256: `20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5` -来源:[`packages/plan/plan-mode/src/index.ts:53`](../packages/plan/plan-mode/src/index.ts) +来源:[`packages/plan/plan-mode/src/index.ts:55`](../packages/plan/plan-mode/src/index.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index 3a1b058f36..caf3ea2b15 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -80,7 +80,7 @@ {"digest":"05a2796621b1ee6c03ef7abe560b25116bb4da4d592312117242a78415a32b04","names":[],"sources":[]}, {"digest":"05d2ae1e0c7f8770f83f9a09047afb39a335d8ac986df3193659aa1e581472cf","names":["packages/interaction/user-approval/src/index.ts#ApprovalPolicy"],"sources":["packages/interaction/user-approval/src/index.ts:68"]}, {"digest":"0657d3ca5ac4e7bf79b00bcf860b1c7159d01a9da137497221ec2f1776e365f7","names":["packages/core/session/src/types.ts#SessionSeq"],"sources":["packages/core/session/src/types.ts:33"]}, - {"digest":"07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235","names":["packages/session/session-title/src/types.ts#SessionTitleModelIdentity","packages/subagent/tool-subagent/src/model-selection.ts#AllowedModelRoute"],"sources":["packages/session/session-title/src/types.ts:20","packages/subagent/tool-subagent/src/model-selection.ts:9"]}, + {"digest":"07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235","names":["packages/session/session-title/src/types.ts#SessionTitleModelIdentity","packages/subagent/tool-subagent/src/model-selection.ts#AllowedModelRoute"],"sources":["packages/session/session-title/src/types.ts:20","packages/subagent/tool-subagent/src/model-selection.ts:11"]}, {"digest":"07eccc9ea2f9b5439d76cc77d5e062936677d43f07a23da749819b0a22ee36b7","names":[],"sources":[]}, {"digest":"09655b34d7f3cf1e9005974de2357de2d4a60deea165d16dac1eadaa6ec539a8","names":[],"sources":[]}, {"digest":"09f3f8dc417f278257202714132f98ba7b52957d7b558c4a04456603890eb363","names":["packages/llm/llm/src/message.ts#SystemMessage"],"sources":["packages/llm/llm/src/message.ts:151"]}, @@ -155,7 +155,7 @@ {"digest":"1f1385dbc3e875c021e387c7096d671d606f22daec51b25c80348735b6bbfa10","names":[],"sources":[]}, {"digest":"1f8c126cfab3df812cd115cfc23e3256f0fa2383400f4ce91ecad313577e59b0","names":["packages/core/session/src/types.ts#TurnEndCancelCause"],"sources":["packages/core/session/src/types.ts:201"]}, {"digest":"1fdad624334d354820dfb3a26e28d0bc9fc1b62a33f87bab63f715b3f4391bfd","names":[],"sources":[]}, - {"digest":"20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5","names":[],"sources":["packages/plan/plan-mode/src/index.ts:53"]}, + {"digest":"20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5","names":[],"sources":["packages/plan/plan-mode/src/index.ts:55"]}, {"digest":"2142e391b9ccb60d487afcf373ce74db98d952f69e8289eddb352a7e16e996c5","names":[],"sources":[]}, {"digest":"2152caf1a71e588e4df2358a806dea24936c1c47131134f01a12939d12cdc0c0","names":["packages/team/agent-team/src/types.ts#TeamMessageSource"],"sources":["packages/team/agent-team/src/types.ts:121"]}, {"digest":"21fb6a90d5068f6a0003b7ab316ed2f56342477146a65c00db0f13c4d8df667d","names":[],"sources":[]}, From a528a6d33c7f0e25dfbe580a856e20b9f0a84a7b Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:16:20 +0800 Subject: [PATCH 034/404] feat(subagent): classify unavailable delegation presets A fresh delegation whose selected preset is unknown or cannot load received the registry's RemoteError, which is not a HarnessError, so the tool result had no error.code. applyChildComposition now converts that RemoteError into SubagentError PRESET_UNAVAILABLE, keeping its message and the original as cause. Restoration still propagates it so the manager reports NOT_RESUMABLE, and other mount failures are unchanged. Refs #7869 --- packages/subagent/subagent/README.i18n.yaml | 4 ++-- packages/subagent/subagent/README.md | 2 +- packages/subagent/subagent/README.zh.md | 2 +- packages/subagent/subagent/src/child-agent.ts | 13 ++++++++++--- .../subagent/tests/continuation-presets.spec.ts | 15 +++++++++++++++ .../tool-subagent/tests/preset-selection.spec.ts | 3 +++ 6 files changed, 32 insertions(+), 7 deletions(-) diff --git a/packages/subagent/subagent/README.i18n.yaml b/packages/subagent/subagent/README.i18n.yaml index ceaac3229a..d89a9ce18b 100644 --- a/packages/subagent/subagent/README.i18n.yaml +++ b/packages/subagent/subagent/README.i18n.yaml @@ -39,8 +39,8 @@ en: bf3175c2218a16dd zh: 4be9271efe71ddb7 /deepseek-ai-dsh-subagent/use-this-package/failure-and-recovery: - en: f5393c65bf8ee460 - zh: d037d42bc967f17b + en: bdb3204a71ee2a8f + zh: 74d7d4e9eca20e2a /deepseek-ai-dsh-subagent/understand-the-implementation: en: 74d91b364b23f88d zh: 19cc558105efe8df diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index dcad891799..916c73346e 100644 --- a/packages/subagent/subagent/README.md +++ b/packages/subagent/subagent/README.md @@ -79,7 +79,7 @@ In-process spawn accepts an independent `agentPreset`; fork and external backend ### Failure and recovery -Starting without the `agents` service rejects with `CONTINUATION_UNAVAILABLE`; an available runtime rejects a missing or replaced parent with `UNAUTHORIZED`. Providers implementing neither execution method are rejected at registration with `UNSUPPORTED_CAPABILITY`; unsupported requested capabilities reject creation with the same code. If a provider is removed or replaced while directory resolution is pending, creation rejects with `PROVIDER_CHANGED` before invoking either provider; retry the delegation against the current registration. Every creation failure below is a `SubagentError`: a child beyond the requested depth rejects with the `SubagentDepthError` subclass and `DEPTH_EXCEEDED`, an invalid runtime `subagentDepth` with `INVALID_DEPTH`, a child that cannot join its creator's preset revision with `PRESET_UNAVAILABLE`, a local child without the working-directory service with `WORKING_DIRECTORY_UNAVAILABLE`, and an out-of-process child whose cwd is relative or not enterable with `INVALID_CWD`. A cold target whose persisted descriptor is corrupt rejects with `NOT_RESUMABLE`, and `structured_output` called while input is pending fails with `STRUCTURED_OUTPUT_PENDING_INPUT`. The caller signal cancels only unpublished work; after publication, `dispose()` cancels the exact activation and waits for its resource cleanup. Creation descendants continue independently; hosts must await `drainDescendants([root])` before disposing the root handle to stop all members and await pending startup. `result` settles after teardown and notifications, carrying output, optional structured data, and a stop reason; capture failures reject it after teardown. Cleanup failures reject `dispose()` and mark the lifecycle end as failed; the result promise and parent notification retain the captured execution result. +Starting without the `agents` service rejects with `CONTINUATION_UNAVAILABLE`; an available runtime rejects a missing or replaced parent with `UNAUTHORIZED`. Providers implementing neither execution method are rejected at registration with `UNSUPPORTED_CAPABILITY`; unsupported requested capabilities reject creation with the same code. If a provider is removed or replaced while directory resolution is pending, creation rejects with `PROVIDER_CHANGED` before invoking either provider; retry the delegation against the current registration. Every creation failure below is a `SubagentError`: a child beyond the requested depth rejects with the `SubagentDepthError` subclass and `DEPTH_EXCEEDED`, an invalid runtime `subagentDepth` with `INVALID_DEPTH`, a fresh child whose selected preset is unknown or cannot load, or that cannot join its creator's preset revision, with `PRESET_UNAVAILABLE`, a local child without the working-directory service with `WORKING_DIRECTORY_UNAVAILABLE`, and an out-of-process child whose cwd is relative or not enterable with `INVALID_CWD`. A cold target whose persisted descriptor is corrupt rejects with `NOT_RESUMABLE`, and `structured_output` called while input is pending fails with `STRUCTURED_OUTPUT_PENDING_INPUT`. The caller signal cancels only unpublished work; after publication, `dispose()` cancels the exact activation and waits for its resource cleanup. Creation descendants continue independently; hosts must await `drainDescendants([root])` before disposing the root handle to stop all members and await pending startup. `result` settles after teardown and notifications, carrying output, optional structured data, and a stop reason; capture failures reject it after teardown. Cleanup failures reject `dispose()` and mark the lifecycle end as failed; the result promise and parent notification retain the captured execution result. ----- diff --git a/packages/subagent/subagent/README.zh.md b/packages/subagent/subagent/README.zh.md index dfe7d1f835..8cc7e6bda9 100644 --- a/packages/subagent/subagent/README.zh.md +++ b/packages/subagent/subagent/README.zh.md @@ -79,7 +79,7 @@ kind: "package-reference" ### 失败与恢复 -缺少 `agents` 服务时,启动请求以 `CONTINUATION_UNAVAILABLE` 拒绝;运行时可用但父级缺失或被替换时,以 `UNAUTHORIZED` 拒绝。未实现任何执行方法的提供方会在注册时以 `UNSUPPORTED_CAPABILITY` 被拒绝;请求不受支持的能力会以同一码使创建失败。如果等待目录解析期间提供方被移除或替换,创建会在调用任何一方之前以 `PROVIDER_CHANGED` 拒绝;调用方可根据当前注册重试委派。以下创建失败均为 `SubagentError`:超出请求深度的子代以 `SubagentDepthError` 子类和 `DEPTH_EXCEEDED` 拒绝,无效的运行时 `subagentDepth` 以 `INVALID_DEPTH` 拒绝,无法加入创建者 preset 版本的子代以 `PRESET_UNAVAILABLE` 拒绝,缺少工作目录服务的本地子代以 `WORKING_DIRECTORY_UNAVAILABLE` 拒绝,cwd 为相对路径或不可进入的进程外子代以 `INVALID_CWD` 拒绝。持久化 descriptor 损坏的冷目标以 `NOT_RESUMABLE` 拒绝,有待处理输入时调用 `structured_output` 以 `STRUCTURED_OUTPUT_PENDING_INPUT` 失败。调用方信号仅取消尚未发布的工作;发布后通过 `dispose()` 取消该次 activation,并等待其资源清理完成。创建后代独立继续运行;宿主必须在释放根句柄前等待 `drainDescendants([root])`,以停止所有成员并等待正在启动的工作。`result` 在清理与通知结束后完成,携带输出、可选结构化数据与停止原因;结果捕获故障在清理后使其拒绝。清理失败使 `dispose()` 拒绝,并将生命周期结束事件标记为失败;结果 promise 与父级通知保留已捕获的执行结果。 +缺少 `agents` 服务时,启动请求以 `CONTINUATION_UNAVAILABLE` 拒绝;运行时可用但父级缺失或被替换时,以 `UNAUTHORIZED` 拒绝。未实现任何执行方法的提供方会在注册时以 `UNSUPPORTED_CAPABILITY` 被拒绝;请求不受支持的能力会以同一码使创建失败。如果等待目录解析期间提供方被移除或替换,创建会在调用任何一方之前以 `PROVIDER_CHANGED` 拒绝;调用方可根据当前注册重试委派。以下创建失败均为 `SubagentError`:超出请求深度的子代以 `SubagentDepthError` 子类和 `DEPTH_EXCEEDED` 拒绝,无效的运行时 `subagentDepth` 以 `INVALID_DEPTH` 拒绝,所选 preset 未知或无法加载、或无法加入创建者 preset 版本的新建子代以 `PRESET_UNAVAILABLE` 拒绝,缺少工作目录服务的本地子代以 `WORKING_DIRECTORY_UNAVAILABLE` 拒绝,cwd 为相对路径或不可进入的进程外子代以 `INVALID_CWD` 拒绝。持久化 descriptor 损坏的冷目标以 `NOT_RESUMABLE` 拒绝,有待处理输入时调用 `structured_output` 以 `STRUCTURED_OUTPUT_PENDING_INPUT` 失败。调用方信号仅取消尚未发布的工作;发布后通过 `dispose()` 取消该次 activation,并等待其资源清理完成。创建后代独立继续运行;宿主必须在释放根句柄前等待 `drainDescendants([root])`,以停止所有成员并等待正在启动的工作。`result` 在清理与通知结束后完成,携带输出、可选结构化数据与停止原因;结果捕获故障在清理后使其拒绝。清理失败使 `dispose()` 拒绝,并将生命周期结束事件标记为失败;结果 promise 与父级通知保留已捕获的执行结果。 ----- diff --git a/packages/subagent/subagent/src/child-agent.ts b/packages/subagent/subagent/src/child-agent.ts index 9f4626641c..89b2a59447 100644 --- a/packages/subagent/subagent/src/child-agent.ts +++ b/packages/subagent/subagent/src/child-agent.ts @@ -25,6 +25,7 @@ import type {} from '@deepseek-ai/dsh-permission-presets' // keeps its model-facing rows on the host plane, where the child already sees // them through the tool registry's global layer. import type {} from '@deepseek-ai/dsh-agent-preset-registry' +import { remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' import { delegationDepthOf } from './depth.ts' import { SubagentError } from './error.ts' @@ -183,8 +184,9 @@ export const SUBAGENT_DELEGATION_CONTEXT * @param parent - creator for fresh delegation; absent during target-only restoration. * @param composition - independent preset and any overrides read from a historical descriptor. * @returns A promise when mounting an independent preset; otherwise completes synchronously. - * @throws {SubagentError} `PRESET_UNAVAILABLE` when the preset service is absent or the - * child cannot join its creator's preset revision. + * @throws {SubagentError} `PRESET_UNAVAILABLE` when the preset service is absent, a fresh + * delegation's preset is unknown or cannot load, or the child cannot join its creator's + * preset revision. Restoration propagates the registry's `RemoteError` unchanged. */ export function applyChildComposition( childCtx: Context, @@ -196,7 +198,12 @@ export function applyChildComposition( if (presets === undefined) { throw new SubagentError('selecting a child agent preset requires the agent-presets service', 'PRESET_UNAVAILABLE') } - return presets.mount(childCtx, composition.agentPreset).then(() => { + const mounted = presets.mount(childCtx, composition.agentPreset) + // Restoration leaves an unavailable preset to its caller's NOT_RESUMABLE classification. + return (parent === undefined ? mounted : mounted.catch((error: unknown) => { + const failure = remoteErrorOf(error) + throw failure === undefined ? error : new SubagentError(failure.message, 'PRESET_UNAVAILABLE', { cause: error }) + })).then(() => { applyChildOverrides(childCtx, composition) }) } diff --git a/packages/subagent/subagent/tests/continuation-presets.spec.ts b/packages/subagent/subagent/tests/continuation-presets.spec.ts index 594be164ac..0cd3e0f69b 100644 --- a/packages/subagent/subagent/tests/continuation-presets.spec.ts +++ b/packages/subagent/subagent/tests/continuation-presets.spec.ts @@ -139,6 +139,21 @@ describe('child preset start validation', () => { expect(adapter.requests).toEqual([]) }) + it('classifies an unknown independent preset as PRESET_UNAVAILABLE and keeps other mount failures', async () => { + const { ctx, parent, adapter } = await setup() + await expect(ctx.subagents.startActivation(startSpec(parent, 'absent'))).rejects.toMatchObject({ + name: 'SubagentError', + code: 'PRESET_UNAVAILABLE', + message: 'Unknown agent preset: absent', + cause: { code: 'agent-preset/not-found' }, + }) + const failure = new Error('binding failed') + vi.spyOn(ctx.agentPresets, 'mount').mockRejectedValueOnce(failure) + await expect(ctx.subagents.startActivation(startSpec(parent, 'reviewing'))).rejects.toBe(failure) + expect(ctx.agents.list().map(agent => agent.id)).toEqual([parent.id]) + expect(adapter.requests).toEqual([]) + }) + it('rolls back an independent spawn when the preset service has unloaded', async () => { const { ctx, parent, adapter, presets } = await setup() await presets.dispose() diff --git a/packages/subagent/tool-subagent/tests/preset-selection.spec.ts b/packages/subagent/tool-subagent/tests/preset-selection.spec.ts index 9bfa7e9e85..920697c323 100644 --- a/packages/subagent/tool-subagent/tests/preset-selection.spec.ts +++ b/packages/subagent/tool-subagent/tests/preset-selection.spec.ts @@ -162,6 +162,7 @@ describe('spawn preset selection', () => { const result = await callSubagent(ctx, { ...args, ...selection }, { agent: parent.agent }) expect(result.isError).toBe(true) expect(text(result)).toContain('Unknown agent preset: absent') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'PRESET_UNAVAILABLE' }) expect(ctx.agents.list()).toEqual([parent.agent]) expect(ctx.sessions.list()).toEqual(sessions) }) @@ -179,6 +180,7 @@ describe('spawn preset selection', () => { const result = await callSubagent(ctx, args, { agent: parent.agent }) expect(result.isError).toBe(true) expect(text(result)).toContain('missing-plugin') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'PRESET_UNAVAILABLE' }) expect(ctx.agents.list()).toEqual([parent.agent]) expect(ctx.sessions.list()).toEqual(sessions) }) @@ -363,6 +365,7 @@ describe('spawn preset selection', () => { const failed = await callSubagent(ctx, args, { agent: handle.agent }) expect(failed.isError).toBe(true) expect(text(failed)).toContain('Unknown agent preset: later') + expect(failed.error?.info).toEqual({ name: 'SubagentError', code: 'PRESET_UNAVAILABLE' }) await ctx.agentPresets.register({ id: 'later', plugins: [] }) ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('reviewed')])) From 80c3a3fe09365fdf62978c33ffda51b74beb5314 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 20:48:51 +0800 Subject: [PATCH 035/404] refactor(plan-mode): keep the code list off the plugin entry The plugin entry exports only the PlanModeError class and its code type; the code list stays module-local in src/error.ts, so the entry adds no value export that verify-plugin-entry-exports would reject. Refs #7869 --- packages/plan/plan-mode/src/error.ts | 2 +- packages/plan/plan-mode/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/plan/plan-mode/src/error.ts b/packages/plan/plan-mode/src/error.ts index e0227893bb..38f98ee1d0 100644 --- a/packages/plan/plan-mode/src/error.ts +++ b/packages/plan/plan-mode/src/error.ts @@ -12,7 +12,7 @@ import { HarnessError } from '@deepseek-ai/dsh-llm' * - `PLAN_REVIEW_INTERRUPTED`: the plan-mode service was reloaded during the review; present the plan again. * - `PLAN_REVISION_REQUESTED`: the user chose to keep planning; revise the plan from the feedback in `message`. */ -export const PLAN_MODE_ERROR_CODES = [ +const PLAN_MODE_ERROR_CODES = [ 'PLAN_NOT_ACTIVE', 'PLAN_REVIEW_INTERRUPTED', 'PLAN_REVISION_REQUESTED', diff --git a/packages/plan/plan-mode/src/index.ts b/packages/plan/plan-mode/src/index.ts index 636165c5e3..685e060339 100644 --- a/packages/plan/plan-mode/src/index.ts +++ b/packages/plan/plan-mode/src/index.ts @@ -43,7 +43,7 @@ declare module '@deepseek-ai/dsh-llm' { } } export type * from './types.ts' -export { PLAN_MODE_ERROR_CODES, PlanModeError, type PlanModeErrorCode } from './error.ts' +export { PlanModeError, type PlanModeErrorCode } from './error.ts' declare module '@deepseek-ai/dsh-session/types' { interface SessionEventMap { From d212c0629af776d321e55dbdf021d8249c0cd0cb Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 21:55:52 +0800 Subject: [PATCH 036/404] refactor(plan-mode,user-questions): import HarnessError from dsh-error PlanModeError is the only base-class use this stack adds to plan-mode, so the package depends on the dependency-free dsh-error instead of reaching the base through dsh-llm; the user-questions test that builds a foreign HarnessError imports it from dsh-error as a dev dependency. Refs #7869 --- docs/module-graph.md | 3 ++- docs/module-graph.zh.md | 3 ++- packages/interaction/user-questions/package.json | 1 + .../interaction/user-questions/tests/user-questions.spec.ts | 3 ++- packages/plan/plan-mode/package.json | 2 ++ packages/plan/plan-mode/src/error.ts | 2 +- packages/plan/plan-mode/tsconfig.json | 3 +++ pnpm-lock.yaml | 6 ++++++ 8 files changed, 19 insertions(+), 4 deletions(-) diff --git a/docs/module-graph.md b/docs/module-graph.md index 1f8dfaee91..6913c9fca6 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -910,6 +910,7 @@ flowchart TD pkg_tool_todo --> pkg_tools pkg_plan_mode --> pkg_agent pkg_plan_mode --> pkg_commands + pkg_plan_mode --> pkg_error pkg_plan_mode --> pkg_llm pkg_plan_mode --> pkg_session pkg_plan_mode --> pkg_session_projection @@ -1814,7 +1815,7 @@ flowchart TD | [`tool-web`](../packages/web/tool-web) | `web` | [`llm`](../packages/llm/llm), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`web`](../packages/web/web) | | [`web-deepseek-api`](../packages/web/web-deepseek-api) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`tool-todo`](../packages/todo/tool-todo) | `todo` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`tools`](../packages/core/tools) | -| [`plan-mode`](../packages/plan/plan-mode) | `plan` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | +| [`plan-mode`](../packages/plan/plan-mode) | `plan` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`command-compact`](../packages/compaction/command-compact) | `compaction` | [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction) | | [`compaction-image-offload`](../packages/compaction/compaction-image-offload) | `compaction` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`agent-instructions`](../packages/context/agent-instructions) | `context` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`home-paths`](../packages/util/home-paths), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index a6070b4f5e..aa668a72c2 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -912,6 +912,7 @@ flowchart TD pkg_tool_todo --> pkg_tools pkg_plan_mode --> pkg_agent pkg_plan_mode --> pkg_commands + pkg_plan_mode --> pkg_error pkg_plan_mode --> pkg_llm pkg_plan_mode --> pkg_session pkg_plan_mode --> pkg_session_projection @@ -1816,7 +1817,7 @@ flowchart TD | [`tool-web`](../packages/web/tool-web) | `web` | [`llm`](../packages/llm/llm), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`web`](../packages/web/web) | | [`web-deepseek-api`](../packages/web/web-deepseek-api) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`tool-todo`](../packages/todo/tool-todo) | `todo` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`tools`](../packages/core/tools) | -| [`plan-mode`](../packages/plan/plan-mode) | `plan` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | +| [`plan-mode`](../packages/plan/plan-mode) | `plan` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`command-compact`](../packages/compaction/command-compact) | `compaction` | [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction) | | [`compaction-image-offload`](../packages/compaction/compaction-image-offload) | `compaction` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`agent-instructions`](../packages/context/agent-instructions) | `context` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`home-paths`](../packages/util/home-paths), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | diff --git a/packages/interaction/user-questions/package.json b/packages/interaction/user-questions/package.json index 3eb448ad83..4665aa742d 100644 --- a/packages/interaction/user-questions/package.json +++ b/packages/interaction/user-questions/package.json @@ -60,6 +60,7 @@ }, "devDependencies": { "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-scope": "workspace:*", "@deepseek-ai/cordis": "workspace:~", diff --git a/packages/interaction/user-questions/tests/user-questions.spec.ts b/packages/interaction/user-questions/tests/user-questions.spec.ts index d76ade47db..a4f3208de1 100644 --- a/packages/interaction/user-questions/tests/user-questions.spec.ts +++ b/packages/interaction/user-questions/tests/user-questions.spec.ts @@ -7,7 +7,8 @@ import UserQuestionService, { type AskUserQuestionAnswer, type AskUserQuestionRequest, } from '@deepseek-ai/dsh-user-questions' -import { createToolResultMessage, createUserMessage, HarnessError, ToolCallId, type ToolSchema, type UserMessage } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' +import { createToolResultMessage, createUserMessage, ToolCallId, type ToolSchema, type UserMessage } from '@deepseek-ai/dsh-llm' import { Session, SessionId, SESSION_FORMAT_VERSION, TOOL_OUTCOME_UNKNOWN } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' diff --git a/packages/plan/plan-mode/package.json b/packages/plan/plan-mode/package.json index b4685d4062..26a6273e2e 100644 --- a/packages/plan/plan-mode/package.json +++ b/packages/plan/plan-mode/package.json @@ -43,6 +43,7 @@ "peerDependencies": { "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-commands": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-projection": "workspace:*", @@ -65,6 +66,7 @@ "@deepseek-ai/dsh-agent-loop": "workspace:*", "@deepseek-ai/dsh-ptc-runtime": "workspace:*", "@deepseek-ai/dsh-commands": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-projection": "workspace:*", diff --git a/packages/plan/plan-mode/src/error.ts b/packages/plan/plan-mode/src/error.ts index 38f98ee1d0..997eb5540e 100644 --- a/packages/plan/plan-mode/src/error.ts +++ b/packages/plan/plan-mode/src/error.ts @@ -4,7 +4,7 @@ * @module @deepseek-ai/dsh-plan-mode/error */ -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' /** * Every machine-routable plan-mode failure: diff --git a/packages/plan/plan-mode/tsconfig.json b/packages/plan/plan-mode/tsconfig.json index f187853290..357509a9f0 100644 --- a/packages/plan/plan-mode/tsconfig.json +++ b/packages/plan/plan-mode/tsconfig.json @@ -14,6 +14,9 @@ { "path": "../../../vendor/cordis" }, + { + "path": "../../util/error" + }, { "path": "../../core/tools" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ca94685474..9d71501a7c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -13061,6 +13061,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:* version: link:../../core/agent + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-llm': specifier: workspace:* version: link:../../llm/llm @@ -13905,6 +13908,9 @@ importers: '@deepseek-ai/dsh-commands': specifier: workspace:* version: link:../../interaction/commands + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-llm': specifier: workspace:* version: link:../../llm/llm From dbd69abfa135f31fbd676240bfeceb542aa4d0da Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 6 Nov 2026 16:52:50 +0800 Subject: [PATCH 037/404] fix(panel): measure adopted Sessions and keep the panel overlay transient - The main width controls restart their measurement when the body adopts its first Session, so a Session opened from the blank home reports its gutter without waiting for a resize. - ConversationLayout gains `shown`: the width controls report null when the body stops showing a Session, and a released Session publishes it as not shown before its layout is dropped. Layouts no longer outlive their Session's binding scope. - The overlay follows its Session's layout and closes once the gutter can dock the panel or the body shows another Session, so it never reopens on its own. - Escape is left to an input method composing text, and focus moves to the toggle when the panel hides while it holds focus. - The client inject list names the context menu, Remote, and connection packages the panel reads, the README states Escape priority and the Chat-only gutter, and the Agent Note describes the turn rail as it is. --- .../2026-11-05-session-panel.i18n.yaml | 10 +-- .../feature/2026-11-05-session-panel.md | 6 +- .../feature/2026-11-05-session-panel.zh.md | 6 +- .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 2 +- packages/client/ui-conversation/README.zh.md | 2 +- .../src/client/contract/slots.ts | 19 +++-- .../src/client/conversation/assembly.ts | 4 +- .../src/client/conversation/layouts.ts | 71 +++++++++++++----- .../skeleton/ConversationWidthControls.tsx | 7 +- .../tests/layouts.client.spec.ts | 75 +++++++++++++++++++ .../tests/skeleton.client.spec.tsx | 29 ++++++- .../client/ui-session-panel/README.i18n.yaml | 4 +- packages/client/ui-session-panel/README.md | 2 +- packages/client/ui-session-panel/README.zh.md | 2 +- packages/client/ui-session-panel/package.json | 4 + .../src/client/SessionPanel.tsx | 45 +++++++++-- .../ui-session-panel/src/client/index.ts | 4 +- .../ui-session-panel/src/client/visibility.ts | 33 +++++++- .../tests/browser-plugin.client.spec.ts | 2 +- .../tests/components.client.spec.tsx | 63 +++++++++++++++- .../tests/visibility.client.spec.ts | 73 +++++++++++++++--- .../client/ui-session-panel/tsconfig.json | 3 + pnpm-lock.yaml | 3 + 24 files changed, 396 insertions(+), 77 deletions(-) create mode 100644 packages/client/ui-conversation/tests/layouts.client.spec.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 index 4bd1f78eff..8fa5341ff8 100644 --- a/.agents/notes/implemented/feature/2026-11-05-session-panel.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-11-05-session-panel.i18n.yaml @@ -12,14 +12,14 @@ 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 + en: f406a8821cdc8dc9 + zh: 42178c0188cb0f2b /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/decision/the-turn-rail-sits-at-the-start-edge: + en: 08e720a4ea75d4d6 + zh: 5e2e5b8452f67d36 /agent-note-session-panel-over-the-conversation-body-s-end-gutter/alternatives-considered: en: 9cf81cde02bf900b zh: 549d92a260541e3d diff --git a/.agents/notes/implemented/feature/2026-11-05-session-panel.md b/.agents/notes/implemented/feature/2026-11-05-session-panel.md index ca4b96e4ab..5b348b9722 100644 --- a/.agents/notes/implemented/feature/2026-11-05-session-panel.md +++ b/.agents/notes/implemented/feature/2026-11-05-session-panel.md @@ -18,7 +18,7 @@ The panel docks only while the gutter between the transcript column and the body 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. +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 it closes once its gutter can dock the panel or the main body shows another Session, so it never reappears on its own. The panel state follows the open overlay's layout source, which the Conversation shell marks as no longer shown when the main body leaves the Session, instead of a component cleanup that React's double mount would also run. 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 @@ -26,9 +26,9 @@ Each section is one list registration with `id`, `order`, and a required `label` 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 sits at 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. +The turn rail sits at the scrollport's start edge with its marks, focus ring, and preview mirrored, leaving the end gutter to the docked panel; its 900px hiding rule guarantees room beside the start-side width handle. ## Alternatives considered 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 index 136ceff8a0..4c3712e197 100644 --- a/.agents/notes/implemented/feature/2026-11-05-session-panel.zh.md +++ b/.agents/notes/implemented/feature/2026-11-05-session-panel.zh.md @@ -18,7 +18,7 @@ Status: implemented 开关和面板读取同一个 source 和同一份插件持有的可见性状态,并用同一个纯函数决定呈现方式。因此开关能如实报告 `aria-expanded`,也知道按下后是切换停靠还是打开浮层;纯 CSS 的容器查询无法把结果告诉正文之外的元素。 -停靠遵循所有会话共用的一个持久化偏好,默认开启。没有空间时,按下开关会为该会话在正文和 composer 区域上方打开临时浮层;它从不改变偏好,宽留白下切换停靠也会关闭浮层。自动隐藏加按需浮层,既保证正文不被遮挡,也让笔记本宽度下的信息依然可达。 +停靠遵循所有会话共用的一个持久化偏好,默认开启。没有空间时,按下开关会为该会话在正文和 composer 区域上方打开临时浮层;它从不改变偏好;该会话的留白可以停靠面板,或主正文切到其他会话时,浮层关闭,因此不会自己重新出现。面板状态跟随打开浮层的会话的布局 source,主正文离开该会话时 Conversation 外壳会把它标记为不再显示;不用组件清理函数实现,因为 React 的双重挂载也会运行它。自动隐藏加按需浮层,既保证正文不被遮挡,也让笔记本宽度下的信息依然可达。 ### 分栏是注册项;面板绘制标题 @@ -26,9 +26,9 @@ Status: implemented 所有贡献方的行都使用 `PanelRow` 原语,使不同包的图标、文字与尾部区域对齐;功能包之间不能共享各自的行组件。 -### 轮次轨道移到起始边 +### 轮次轨道位于起始边 -轮次轨道原先贴在滚动容器末端边缘,停靠面板现在占用这里。轨道连同刻度、焦点环和预览镜像到起始边;原有的 900px 隐藏规则仍保证它旁边有足够空间容纳起始侧的宽度拖拽条。 +轮次轨道连同刻度、焦点环和预览位于滚动容器的起始边,末端留白留给停靠面板;它的 900px 隐藏规则保证旁边有足够空间容纳起始侧的宽度拖拽条。 ## Alternatives considered diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 06d21c9a63..cab118cd76 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: 1d9c21bd934d1a3b - zh: 3c47d27ea72b2a2e + en: 1939628ccfabb23d + zh: b0882827f338cf8c /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 25bc4dab22..7a3bf52c8a 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -120,7 +120,7 @@ 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 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, again when the body adopts its first Session, and reset to zero when they stop showing the Session; `shown` says whether the main body shows the Session. The gutter stays zero while a View other than the shipped Chat View (`chat`) is active, because those Views fill the body; a View registered under another id reads zero as well. A Session's layout is dropped when its binding scope is released. 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. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index 8f9964211f..90ae97ed3c 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -120,7 +120,7 @@ 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 占满正文)时,它保持为零。 +活跃 Session 的主 occurrence 还会在正文内渲染 `conversation.session.panel` 落位,与宽度拖拽条同层,位于滚动容器之外;嵌入式 occurrence 和空白首页不渲染它。占位组件相对正文定位,正文持有正文轴线与 composer 区域高度 `--dsh-composer-height`。`ctx.uiConversation.layouts.source(sessionId)` 发布该 Session 的 `ConversationLayout`:`endGutter` 是正文列末端边缘到正文末端边缘的距离,由主宽度控件在每次测量与拖拽帧后写入,正文接上第一个 Session 时也会写入一次,不再显示该 Session 时归零;`shown` 表示主正文当前是否显示该 Session。激活的是内置 Chat View(`chat`)以外的 View 时留白保持为零,因为这类 View 占满正文;以其他 id 注册的 View 同样读到零。Session 的绑定 scope 释放时,它的布局随之丢弃。 常驻 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,因此光标回到草稿原来的位置而不是开头。 diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index 9dbe00d8bb..d0520f411b 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -443,9 +443,12 @@ 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). + * transcript column. Only the shipped Chat View (`chat`) follows it; a View + * registered under another id, and any View that fills the body, reads zero. */ readonly endGutter: number + /** Whether the main Conversation body currently shows the Session. */ + readonly shown: boolean } /** The header corner's occupant derives its state from standard Session props. */ @@ -500,9 +503,10 @@ export interface ConversationInjected { /** * 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. + * @param endGutter - space between the transcript column's end edge and the body's end edge, in CSS px; + * null when the body stops showing the Session. */ - reportEndGutter: (endGutter: number) => void + reportEndGutter: (endGutter: number | null) => void } /** Business callbacks injected into the strict Session body. */ @@ -696,11 +700,12 @@ export interface ConversationWidthControlsInputProps { /** 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. + * Receive the end gutter after each measurement and drag frame, and null when + * the controls unmount or a new callback replaces this one. + * @param endGutter - space between the transcript column's end edge and the body's end edge, in CSS px; + * null when the body stops showing the Session. */ - onEndGutter: (endGutter: number) => void + onEndGutter: (endGutter: number | null) => 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 d879921d9b..91348340d9 100644 --- a/packages/client/ui-conversation/src/client/conversation/assembly.ts +++ b/packages/client/ui-conversation/src/client/conversation/assembly.ts @@ -213,7 +213,7 @@ export class UiConversation extends Service { /** 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() + readonly layouts: ConversationLayouts private readonly bindings = new WeakMapWithValues() private readonly images: HistoricalImageCache @@ -229,6 +229,7 @@ export class UiConversation extends Service { this.userText = new UserTextRegistry(ctx) this.interactions = new ConversationInteractionRegistry(ctx) this.images = new HistoricalImageCache(ctx, sessions) + this.layouts = new ConversationLayouts(sessionId => sessions.binding(sessionId)?.ctx) const rebuild = (): void => { for (const record of this.bindings.values) record.binding.rebuild() } @@ -250,6 +251,7 @@ export class UiConversation extends Service { disposeViews() disposeEvents() for (const record of [...this.bindings.values]) this.drop(record, true) + this.layouts.dispose() } }, 'ui-conversation assembly') } diff --git a/packages/client/ui-conversation/src/client/conversation/layouts.ts b/packages/client/ui-conversation/src/client/conversation/layouts.ts index 9caa7c35cf..5923c4ad39 100644 --- a/packages/client/ui-conversation/src/client/conversation/layouts.ts +++ b/packages/client/ui-conversation/src/client/conversation/layouts.ts @@ -1,46 +1,62 @@ /** Per-Session geometry of the main Conversation body, published through `ctx.uiConversation.layouts`. */ +import type { Context } from '@deepseek-ai/cordis' 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 }) +const NO_LAYOUT: ConversationLayout = Object.freeze({ endGutter: 0, shown: false }) interface LayoutEntry { /** Last end gutter the main body's width controls measured, in CSS px. */ measured: number + /** Whether the main body shows the Session. */ + shown: boolean /** Whether the Session's active View follows the transcript column; false before the first activation. */ followsTranscript: boolean readonly store: SnapshotStore + /** Withdraw the release registered on the Session's scope. */ + release: () => void } /** - * 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`. + * Layout facts of the main Conversation body, kept per Session until the + * Session's binding scope is released. The Conversation shell writes them: + * the main body's width controls report the measured end gutter and when the + * body stops showing the Session, and View activation reports whether the + * active View follows the transcript column (only Chat does). 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() + /** + * @param scopeOf - the binding scope of a Session, whose release drops the + * Session's layout; undefined keeps the layout until `dispose`. + */ + constructor(private readonly scopeOf: (sessionId: SessionId) => Context | undefined) {} + /** * 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. + * @returns a source whose identity is stable while the Session stays bound and whose snapshot keeps its identity until a fact 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. + * Record the end gutter the main body measured while showing a Session, or that it stopped showing it. + * @param sessionId - Session the main body shows or showed. + * @param endGutter - space between the transcript column's end edge and the body's end edge, in CSS px; + * null when the body stops showing the Session. */ - measure(sessionId: SessionId, endGutter: number): void { + measure(sessionId: SessionId, endGutter: number | null): void { + // A Session already released is not shown; recording that would only recreate its entry. + if (endGutter === null && !this.entries.has(sessionId)) return const entry = this.entryOf(sessionId) - entry.measured = Math.max(0, endGutter) + entry.shown = endGutter !== null + entry.measured = endGutter === null ? 0 : Math.max(0, endGutter) this.publish(entry) } @@ -55,18 +71,35 @@ export class ConversationLayouts { this.publish(entry) } + /** Drop every Session's layout and withdraw the releases registered on their scopes. */ + dispose(): void { + for (const entry of [...this.entries.values()]) entry.release() + this.entries.clear() + } + 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) + const existing = this.entries.get(sessionId) + if (existing !== undefined) return existing + const entry: LayoutEntry = { + measured: 0, shown: false, followsTranscript: false, store: createSnapshotStore(NO_LAYOUT), release: () => {}, + } + this.entries.set(sessionId, entry) + const scope = this.scopeOf(sessionId) + if (scope !== undefined) { + // Readers holding the source learn that a released Session is no longer shown. + const dispose = scope.effect(() => () => { + this.entries.delete(sessionId) + entry.store.set(NO_LAYOUT) + }, 'ui-conversation layout') + entry.release = () => { void dispose() } } 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 }) + const current = entry.store.getSnapshot() + if (current.endGutter === endGutter && current.shown === entry.shown) return + entry.store.set(endGutter === 0 && !entry.shown ? NO_LAYOUT : { endGutter, shown: entry.shown }) } } diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx index 1b35ee6137..63c08829a3 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx @@ -152,6 +152,9 @@ export function ConversationWidthControls({ container, phase, onEndGutter }: Con report.current((column - resolveContentWidth(column, preference)) / 2) }, []) + // A new callback means the body adopted a Session without remounting or + // resizing: the measurement restarts so that Session gets the current gutter, + // and the callback it replaces receives its final zero. useLayoutEffect(() => { if (container === null) return const observer = new ResizeObserver(() => { publishWidths(container) }) @@ -159,9 +162,9 @@ export function ConversationWidthControls({ container, phase, onEndGutter }: Con publishWidths(container) return () => { observer.disconnect() - report.current(0) + onEndGutter(null) } - }, [container, publishWidths]) + }, [container, onEndGutter, publishWidths]) const onStart = useCallback((): number => { if (container === null) return 680 diff --git a/packages/client/ui-conversation/tests/layouts.client.spec.ts b/packages/client/ui-conversation/tests/layouts.client.spec.ts new file mode 100644 index 0000000000..792fe539b4 --- /dev/null +++ b/packages/client/ui-conversation/tests/layouts.client.spec.ts @@ -0,0 +1,75 @@ +import { Context } from '@deepseek-ai/cordis' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { describe, expect, it } from 'vitest' +import { ConversationLayouts } from '../src/client/conversation/layouts.ts' + +const S1 = 's1' as SessionId +const S2 = 's2' as SessionId + +describe('ConversationLayouts', () => { + it('publishes the measured gutter and whether the body shows the Session, while Chat is active', () => { + const layouts = new ConversationLayouts(() => undefined) + const source = layouts.source(S1) + expect(source.getSnapshot()).toEqual({ endGutter: 0, shown: false }) + layouts.measure(S1, 400) + // Before a View activates, nothing follows the transcript column. + expect(source.getSnapshot()).toEqual({ endGutter: 0, shown: true }) + layouts.activate(S1, true) + expect(source.getSnapshot()).toEqual({ endGutter: 400, shown: true }) + layouts.measure(S1, -5) + expect(source.getSnapshot()).toEqual({ endGutter: 0, shown: true }) + layouts.measure(S1, 360) + layouts.activate(S1, false) + expect(source.getSnapshot()).toEqual({ endGutter: 0, shown: true }) + layouts.activate(S1, true) + layouts.measure(S1, null) + expect(source.getSnapshot()).toEqual({ endGutter: 0, shown: false }) + expect(layouts.source(S2).getSnapshot()).toEqual({ endGutter: 0, shown: false }) + }) + + it('keeps the snapshot identity until a fact changes and notifies only on changes', () => { + const layouts = new ConversationLayouts(() => undefined) + const source = layouts.source(S1) + layouts.activate(S1, true) + layouts.measure(S1, 400) + const first = source.getSnapshot() + let notified = 0 + const off = source.subscribe(() => { notified += 1 }) + layouts.measure(S1, 400) + layouts.activate(S1, true) + expect(source.getSnapshot()).toBe(first) + expect(notified).toBe(0) + layouts.measure(S1, 380) + expect(notified).toBe(1) + off() + }) + + it('drops a Session layout when its scope is released, and every layout on dispose', async () => { + const root = new Context() + const one = root.plugin(() => {}) + const two = root.plugin(() => {}) + await Promise.all([one, two]) + const scopes = new Map([[S1, one], [S2, two]]) + const layouts = new ConversationLayouts(sessionId => scopes.get(sessionId)?.ctx) + const first = layouts.source(S1) + expect(layouts.source(S1)).toBe(first) + layouts.activate(S1, true) + layouts.measure(S1, 400) + const seen: unknown[] = [] + first.subscribe(() => { seen.push(first.getSnapshot()) }) + // A released Session no longer resolves a binding scope, and its readers see it hidden. + await scopes.get(S1)?.dispose() + scopes.delete(S1) + expect(seen).toEqual([{ endGutter: 0, shown: false }]) + // The body's final report after the release recreates nothing. + layouts.measure(S1, null) + expect(layouts.source(S1)).not.toBe(first) + expect(layouts.source(S1).getSnapshot()).toEqual({ endGutter: 0, shown: false }) + const second = layouts.source(S2) + layouts.dispose() + expect(layouts.source(S2)).not.toBe(second) + // A Session without a scope keeps its layout until dispose. + const unscoped = layouts.source('s3' as SessionId) + expect(layouts.source('s3' as SessionId)).toBe(unscoped) + }) +}) diff --git a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx index c82b03cb77..69de5bd9f8 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -22,6 +22,7 @@ import { createConversationStore } from '../src/client/stores.ts' import { SessionInputShell } from '../src/client/input/facade.ts' import { en, zh } from '../src/client/locales.ts' import { ConversationContent } from '../src/client/skeleton/ConversationContent.tsx' +import { ConversationWidthControls } from '../src/client/skeleton/ConversationWidthControls.tsx' import { ConversationHeader } from '../src/client/skeleton/ConversationHeader.tsx' import { ConversationMainPanel } from '../src/client/skeleton/ConversationMainPanel.tsx' import { ConversationSession, ConversationSessionHeader } from '../src/client/skeleton/ConversationSession.tsx' @@ -33,7 +34,7 @@ import type { InputBarProps } from '../src/client/skeleton/InputBar.tsx' import type { ComposerBarOwnerProps, ConversationContentInputProps, ConversationContentProps, ConversationHeaderLineageOwnerProps, ConversationSessionHeaderSlotProps, ConversationSessionSlotProps, ConversationSlotProps, - ConversationViewActionsOwnerProps, ConversationViewsProps, HeroFrameOwnerProps, + ConversationViewActionsOwnerProps, ConversationViewsProps, HeroFrameOwnerProps, ConversationWidthControlsProps, } from '../src/client/contract/slots.ts' import type { ViewTab } from '../src/client/contract/views.ts' @@ -207,7 +208,7 @@ function mount( 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 gutters: (number | null)[] = [] 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') { @@ -1084,7 +1085,7 @@ describe('ConversationRoot resident composer', () => { expect(b.view.container.querySelector('[data-width-handle]')).toBeNull() }) - it('reports the end gutter after each measurement and drag frame, and zero on unmount', () => { + it('reports the end gutter after each measurement and drag frame, and that it stops showing the Session 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 }) @@ -1111,7 +1112,27 @@ describe('ConversationRoot resident composer', () => { } } b.view.unmount() - expect(b.gutters.at(-1)).toBe(0) + expect(b.gutters.at(-1)).toBeNull() + }) + + it('reports the end gutter to a newly adopted Session without a resize, and only once per callback', () => { + const body = document.createElement('div') + document.body.append(body) + Object.defineProperty(body, 'offsetWidth', { value: 1600, configurable: true }) + const props = (onEndGutter: (gutter: number | null) => void) => ({ container: body, phase: 'active', onEndGutter }) as + Pick as ConversationWidthControlsProps + const blank = vi.fn<(gutter: number | null) => void>() + const adopted = vi.fn<(gutter: number | null) => void>() + const view = render() + expect(blank).toHaveBeenLastCalledWith(340) + view.rerender() + expect(blank).toHaveBeenLastCalledWith(null) + expect(adopted.mock.calls).toEqual([[340]]) + view.rerender() + expect(adopted).toHaveBeenCalledOnce() + view.unmount() + expect(adopted).toHaveBeenLastCalledWith(null) + body.remove() }) it('renders the Session panel seat only for the main occurrence of an active Session', () => { diff --git a/packages/client/ui-session-panel/README.i18n.yaml b/packages/client/ui-session-panel/README.i18n.yaml index 0d5adc4dd8..f907fc7722 100644 --- a/packages/client/ui-session-panel/README.i18n.yaml +++ b/packages/client/ui-session-panel/README.i18n.yaml @@ -18,8 +18,8 @@ en: d7818d67e981be3c zh: c7c0c704d5ef8b34 /deepseek-ai-dsh-client-ui-session-panel/use-this-package/docking-and-the-overlay: - en: 1d99ccdba0457d10 - zh: 81833d87548d3225 + en: c10ebd54b9412ac1 + zh: a5e878ab049c44a9 /deepseek-ai-dsh-client-ui-session-panel/use-this-package/contribute-a-section: en: 46c0aa93bceeaf0d zh: 478acadcd8828db6 diff --git a/packages/client/ui-session-panel/README.md b/packages/client/ui-session-panel/README.md index f0ce954d68..776ac127d0 100644 --- a/packages/client/ui-session-panel/README.md +++ b/packages/client/ui-session-panel/README.md @@ -31,7 +31,7 @@ The `@deepseek-ai/dsh-web-app` bundle loads this package by default. The toggle 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. +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. A modal above the page, an input method composing text, and a handler that already took the key, such as an open menu's, keep Escape; otherwise the overlay takes it first, so with the overlay open the first Escape from the composer closes the overlay and does not count toward stopping a running turn. Closing it does not change the docking preference. At most one Session's overlay is open; it closes once the gutter widens enough to dock and once the main body shows another Session, and switching back does not reopen it. When the panel hides while focus is inside it, focus moves to the toggle. ### Contribute a section diff --git a/packages/client/ui-session-panel/README.zh.md b/packages/client/ui-session-panel/README.zh.md index 86b6f8b12c..92130c15d4 100644 --- a/packages/client/ui-session-panel/README.zh.md +++ b/packages/client/ui-session-panel/README.zh.md @@ -31,7 +31,7 @@ kind: "package-reference" 正文列到对话区末端边缘的留白不少于 344px 时,面板停靠:与正文列及其宽度手柄保持 48px 间距,面板最小宽度 280px,外加 16px 边距。停靠时面板宽 280–340px,位于标题栏下方 12px,内容在面板内滚动。此时按开关会切换所有会话共用的停靠偏好,偏好存放在 `localStorage` 的 `dsh.sessionPanel.pinned` 中;默认停靠。 -留白更窄时隐藏停靠面板,保证不遮挡正文。窗口变窄、展开右侧栏、把正文列拖宽,以及切换到 Chat 以外的视图(这些视图占满对话区)都会如此。此时按开关,面板以更强的阴影浮在正文上方,位于输入框区域之上,且不遮挡输入框。浮层可以用开关关闭,也会在按 Esc 时,或在面板、开关和任何已打开的菜单(例如行的上下文菜单)之外按下指针时关闭;焦点原本在面板内时,按 Esc 后焦点回到开关,页面上方有模态框时 Esc 归模态框处理。关闭浮层不改变停靠偏好。同一时间最多一个会话的浮层处于打开状态,在宽留白下切换停靠也会关闭它。 +留白更窄时隐藏停靠面板,保证不遮挡正文。窗口变窄、展开右侧栏、把正文列拖宽,以及切换到 Chat 以外的视图(这些视图占满对话区)都会如此。此时按开关,面板以更强的阴影浮在正文上方,位于输入框区域之上,且不遮挡输入框。浮层可以用开关关闭,也会在按 Esc 时,或在面板、开关和任何已打开的菜单(例如行的上下文菜单)之外按下指针时关闭;焦点原本在面板内时,按 Esc 后焦点回到开关。页面上方有模态框、输入法正在组字,或已有处理程序(例如打开的菜单)接手了这次按键时,Esc 不归浮层;其余情况由浮层先处理,因此浮层打开时,在输入框按下的第一次 Esc 只关闭浮层,不计入停止当前轮次的连按。关闭浮层不改变停靠偏好。同一时间最多一个会话的浮层处于打开状态;留白变宽到可以停靠时,以及主正文切到其他会话时,浮层都会关闭,切回来也不会重新打开。面板隐藏时如果焦点在面板内,焦点移到开关。 ### 贡献分栏 diff --git a/packages/client/ui-session-panel/package.json b/packages/client/ui-session-panel/package.json index 44aa1ebc95..a67d989b2a 100644 --- a/packages/client/ui-session-panel/package.json +++ b/packages/client/ui-session-panel/package.json @@ -39,6 +39,7 @@ "@deepseek-ai/dsh-api-remotes": "workspace:*", "@deepseek-ai/dsh-api-session-controller": "workspace:*", "@deepseek-ai/dsh-api-workspace-controller": "workspace:*", + "@deepseek-ai/dsh-client-connection": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", @@ -68,7 +69,10 @@ "dsh": { "client": { "inject": [ + "@deepseek-ai/dsh-api-remotes", + "@deepseek-ai/dsh-client-connection", "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-client-ui-context-menu", "@deepseek-ai/dsh-client-ui-conversation", "@deepseek-ai/dsh-client-ui-primitives" ], diff --git a/packages/client/ui-session-panel/src/client/SessionPanel.tsx b/packages/client/ui-session-panel/src/client/SessionPanel.tsx index ffe655bc7d..39ff023b89 100644 --- a/packages/client/ui-session-panel/src/client/SessionPanel.tsx +++ b/packages/client/ui-session-panel/src/client/SessionPanel.tsx @@ -1,6 +1,6 @@ /** 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 { useCallback, useEffect, useMemo, useRef, type FocusEvent, type ReactNode } from 'react' +import { isBehindModal, observeComposition } 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' @@ -8,9 +8,10 @@ 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. + * toggle and open menus, such as a row's context menu, count as inside; a + * modal above the page and an input method composing text keep Escape, as + * does a handler that already took it. 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. @@ -19,6 +20,7 @@ import css from './SessionPanel.module.css' function useOverlayDismissal(panel: { readonly current: HTMLElement | null }, open: boolean, toggleId: string, close: () => void): void { useEffect(() => { if (!open) return + const composition = observeComposition(document) const inside = (target: EventTarget | null): boolean => target instanceof Element && ( panel.current?.contains(target) === true || document.getElementById(toggleId)?.contains(target) === true @@ -28,7 +30,7 @@ function useOverlayDismissal(panel: { readonly current: HTMLElement | null }, op if (!inside(event.target)) close() } const onKeyDown = (event: KeyboardEvent): void => { - if (event.key !== 'Escape' || event.defaultPrevented || isBehindModal(panel.current)) return + if (event.key !== 'Escape' || composition.guards(event) || event.defaultPrevented || isBehindModal(panel.current)) return event.preventDefault() const focused = panel.current?.contains(document.activeElement) === true close() @@ -39,10 +41,38 @@ function useOverlayDismissal(panel: { readonly current: HTMLElement | null }, op return () => { document.removeEventListener('pointerdown', onPointerDown) document.removeEventListener('keydown', onKeyDown) + composition.dispose() } }, [panel, open, toggleId, close]) } +/** + * Hand focus to the toggle when the panel hides with the keyboard inside it, + * as when a narrower gutter hides the docked panel: the focused control is + * gone and the toggle is the control that brings it back. + * @param hidden - whether the panel renders nothing. + * @param toggleId - id of the Session's toggle. + * @returns focus handlers for the panel element. + */ +function useFocusReturn(hidden: boolean, toggleId: string): { + readonly onFocus: () => void + readonly onBlur: (event: FocusEvent) => void +} { + const inside = useRef(false) + useEffect(() => { + if (!hidden || !inside.current) return + inside.current = false + document.getElementById(toggleId)?.focus({ preventScroll: true }) + }, [hidden, toggleId]) + return useMemo(() => ({ + onFocus: () => { inside.current = true }, + onBlur: (event) => { + // Removal can report no next target; only a move to another element leaves the panel. + if (event.relatedTarget instanceof Element && !event.currentTarget.contains(event.relatedTarget)) inside.current = false + }, + }), []) +} + /** * 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. @@ -63,6 +93,7 @@ export function SessionPanel({ : { presentation, dismissOverlay }, [presentation, dismissOverlay]) useOverlayDismissal(panel, presentation === 'overlay', toggleElementId(sessionId), dismissOverlay) + const focus = useFocusReturn(owner === undefined, toggleElementId(sessionId)) if (owner === undefined) return null return (
@@ -95,7 +95,7 @@ None; the package never assembles or sends provider requests. 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 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 working folder. - **No section customization** — every live section shows; hiding or reordering sections from the panel is not offered. diff --git a/packages/client/ui-session-panel/README.zh.md b/packages/client/ui-session-panel/README.zh.md index 92130c15d4..f9068aa13b 100644 --- a/packages/client/ui-session-panel/README.zh.md +++ b/packages/client/ui-session-panel/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -`dsh-client-ui-session-panel` 在会话标题栏加一个开关,用来显示或隐藏一块汇总当前会话信息的悬浮面板。主对话区末端留白放得下面板时,面板停靠在留白里;放不下时,按需浮在对话正文上方。面板只绘制分栏标题,分栏内容交给注册分栏的插件;本包内置「环境」分栏及其项目目录行。 +`dsh-client-ui-session-panel` 在会话标题栏加一个开关,用来显示或隐藏一块汇总当前会话信息的悬浮面板。主对话区末端留白放得下面板时,面板停靠在留白里;放不下时,按需浮在对话正文上方。面板只绘制分栏标题,分栏内容交给注册分栏的插件;本包内置「环境」分栏及其工作目录行。 ## 目录 @@ -38,7 +38,7 @@ kind: "package-reference" 一个分栏是 `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。 +多个插件共用一个标题时,把行注册到分栏拥有者的行 slot 中。内置「环境」分栏(`id: 'environment'`,`order: 0`)声明 `conversation.session.panel.environment.row`;其 `project` 行(`order: 0`)显示会话的工作目录:`workingDirectory` 投影记录的当前目录;投影尚未送达或没有记录时,依次取会话创建时所在的目录、列出本会话的工作区目录。该行先显示目录名,再以三级文字色显示父目录,放不下时以省略号截断;悬停提示写明工作目录并给出完整路径。两处都把宿主家目录缩写为 `~`。右键该行或点其「更多」按钮会打开共享的 `directory` 上下文菜单。拥有共享分栏的插件用同样方式声明自己的行 slot。 面板隐藏时也要可见的标记(例如需要处理的红点)放进 `conversation.session.panel.indicator` 列表。每个占位都带有说明自身的文字,这些文字会成为开关无障碍名称的一部分。 @@ -64,7 +64,7 @@ kind: "package-reference" | [`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) | 项目目录行 | +| [`src/client/ProjectRow.tsx`](src/client/ProjectRow.tsx) | 工作目录行 |
@@ -95,7 +95,7 @@ kind: "package-reference" 以下限制定义的是当前包的约束,而非任务待办清单。 - **笔记本宽度下使用浮层而非停靠**——在默认正文宽度下,对话区宽度需约 1608px 以上才能停靠;更窄时使用浮层。通过把正文列移开来停靠属于另一项布局决策。 -- **没有运行环境行**——客户端没有区分本机、SSH 主机或沙箱模式的会话级信息,因此「环境」分栏只显示项目目录。 +- **没有运行环境行**——客户端没有区分本机、SSH 主机或沙箱模式的会话级信息,因此「环境」分栏只显示工作目录。 - **不能自定义分栏**——所有有内容的分栏都会显示;面板不提供隐藏或重新排序分栏的功能。 diff --git a/packages/client/ui-session-panel/locale/de.json b/packages/client/ui-session-panel/locale/de.json index 251422de2d..a923a789fd 100644 --- a/packages/client/ui-session-panel/locale/de.json +++ b/packages/client/ui-session-panel/locale/de.json @@ -1,6 +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." + "description": "Ein schwebender Bereich, der sich über die Sitzungskopfzeile öffnet und Informationen zur aktuellen Sitzung bündelt, etwa ihren Arbeitsordner." } } diff --git a/packages/client/ui-session-panel/locale/en.json b/packages/client/ui-session-panel/locale/en.json index b461d8432e..145e9f3b27 100644 --- a/packages/client/ui-session-panel/locale/en.json +++ b/packages/client/ui-session-panel/locale/en.json @@ -1,6 +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." + "description": "A floating panel opened from the Session header that gathers facts about the current Session, such as its working folder." } } diff --git a/packages/client/ui-session-panel/locale/es.json b/packages/client/ui-session-panel/locale/es.json index ef7f34e387..07df80440d 100644 --- a/packages/client/ui-session-panel/locale/es.json +++ b/packages/client/ui-session-panel/locale/es.json @@ -1,6 +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." + "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 carpeta de trabajo." } } diff --git a/packages/client/ui-session-panel/locale/fr.json b/packages/client/ui-session-panel/locale/fr.json index 289ee3e312..e41938ca97 100644 --- a/packages/client/ui-session-panel/locale/fr.json +++ b/packages/client/ui-session-panel/locale/fr.json @@ -1,6 +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." + "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 travail." } } diff --git a/packages/client/ui-session-panel/locale/ja.json b/packages/client/ui-session-panel/locale/ja.json index deb479ceca..34c7ba38b2 100644 --- a/packages/client/ui-session-panel/locale/ja.json +++ b/packages/client/ui-session-panel/locale/ja.json @@ -1,6 +1,6 @@ { "meta": { "title": "セッションパネル", - "description": "セッションのヘッダーから開くフローティングパネルで、プロジェクトディレクトリなど現在のセッションに関する情報をまとめて表示します。" + "description": "セッションのヘッダーから開くフローティングパネルで、作業フォルダーなど現在のセッションに関する情報をまとめて表示します。" } } diff --git a/packages/client/ui-session-panel/locale/pt.json b/packages/client/ui-session-panel/locale/pt.json index b5e3f34378..770e3888b4 100644 --- a/packages/client/ui-session-panel/locale/pt.json +++ b/packages/client/ui-session-panel/locale/pt.json @@ -1,6 +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." + "description": "Um painel flutuante aberto pelo cabeçalho da sessão que reúne informações da sessão atual, como a pasta de trabalho." } } diff --git a/packages/client/ui-session-panel/locale/ru.json b/packages/client/ui-session-panel/locale/ru.json index 7ac5e13e5e..0b4488b2df 100644 --- a/packages/client/ui-session-panel/locale/ru.json +++ b/packages/client/ui-session-panel/locale/ru.json @@ -1,6 +1,6 @@ { "meta": { "title": "Панель сеанса", - "description": "Плавающая панель, которая открывается из заголовка сеанса и собирает сведения о текущем сеансе, например его каталог проекта." + "description": "Плавающая панель, которая открывается из заголовка сеанса и собирает сведения о текущем сеансе, например его рабочую папку." } } diff --git a/packages/client/ui-session-panel/locale/zh.json b/packages/client/ui-session-panel/locale/zh.json index f7fb68e766..3410f86a55 100644 --- a/packages/client/ui-session-panel/locale/zh.json +++ b/packages/client/ui-session-panel/locale/zh.json @@ -1,6 +1,6 @@ { "meta": { "title": "会话面板", - "description": "在会话标题栏打开悬浮面板,集中展示项目目录等与当前会话相关的信息。" + "description": "在会话标题栏打开悬浮面板,集中展示工作目录等与当前会话相关的信息。" } } diff --git a/packages/client/ui-session-panel/package.json b/packages/client/ui-session-panel/package.json index a67d989b2a..4aa30b66c3 100644 --- a/packages/client/ui-session-panel/package.json +++ b/packages/client/ui-session-panel/package.json @@ -51,6 +51,7 @@ "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-util-workspace-path": "workspace:*", + "@deepseek-ai/dsh-working-directory": "workspace:*", "@deepseek-ai/dsh-workspace": "workspace:*", "@testing-library/react": "^16.3.3", "clsx": "^2.0.0", 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..fce60b0571 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/ProjectRow.module.css @@ -0,0 +1,35 @@ +/* [name] · [parent]: the name keeps its width up to the row, and the parent + takes the remaining space and clips with an ellipsis. */ + +.folder { + display: flex; + align-items: baseline; + min-width: 0; + overflow: hidden; + white-space: nowrap; +} + +.folder:focus-visible { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: 1px; +} + +.name { + flex: 0 1 auto; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; +} + +.parent { + flex: 0 1000 auto; + min-width: 0; + overflow: hidden; + color: var(--dsw-alias-label-tertiary); + text-overflow: ellipsis; +} + +.parent::before { + padding: 0 4px; + content: '·'; +} diff --git a/packages/client/ui-session-panel/src/client/ProjectRow.tsx b/packages/client/ui-session-panel/src/client/ProjectRow.tsx index b0920175bf..95655d1a00 100644 --- a/packages/client/ui-session-panel/src/client/ProjectRow.tsx +++ b/packages/client/ui-session-panel/src/client/ProjectRow.tsx @@ -1,25 +1,36 @@ -/** Environment row naming the Session's project directory. */ +/** Environment row naming the Session's working folder. */ 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 { IconFolderCloseRegular, PanelRow, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' +import { abbreviateHomePath, pathPartsOf } from '@deepseek-ai/dsh-util-workspace-path' +import type {} from '@deepseek-ai/dsh-working-directory/types' import type { ProjectRowProps } from './slots.ts' +import css from './ProjectRow.module.css' + +const ROOT = /^(?:[/\\]|[A-Za-z]:[/\\])$/ /** - * 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. + * Render the Session's working folder as its name followed by its parent + * folder, with the label and the full path in the tooltip. The folder is the + * Session's current working directory; before that projection arrives, or + * when it records none, it is the directory the Session was created in, else + * the Workspace that lists the Session. Paths under the Host account home + * start with `~`. The row and its More button open the directory context menu. + * @param props - Session values, the working directory projection, 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, + sessionId, useProjection, useWorkspaces, useSessions, useHost, useContextMenu, renderFactorySlot, t, }: ProjectRowProps): ReactNode { - const workspacePath = useWorkspaces(snapshot => snapshot.items.find(item => item.sessionIds.includes(sessionId))?.path) + const current = useProjection('workingDirectory') const createdIn = useSessions(snapshot => snapshot.byId[sessionId]?.cwd) + const workspacePath = useWorkspaces(snapshot => snapshot.items.find(item => item.sessionIds.includes(sessionId))?.path) const home = useHost(facts => facts.home) const { getTriggerProps } = useContextMenu() - const path = workspacePath ?? createdIn + const path = current ?? createdIn ?? workspacePath if (path === undefined) return null + const shown = abbreviateHomePath(path, home) + const { directory, name } = pathPartsOf(shown) + const parent = ROOT.test(directory) ? directory : directory.replace(/[/\\]+$/, '') const target = { kind: 'directory', value: { sessionId, path } } as const return ( - + + + {name} + {parent !== '' && {parent}} + + ) } diff --git a/packages/client/ui-session-panel/src/client/locales.ts b/packages/client/ui-session-panel/src/client/locales.ts index bdab6fdd5d..6c92a540e8 100644 --- a/packages/client/ui-session-panel/src/client/locales.ts +++ b/packages/client/ui-session-panel/src/client/locales.ts @@ -9,7 +9,8 @@ export const zh = { 'toggle.show': '显示会话面板', 'toggle.hide': '隐藏会话面板', 'section.environment': '环境', - 'project.actions': '项目目录操作', + 'project.label': '工作目录', + 'project.actions': '工作目录操作', } as const /** Every key of the `sessionPanel` namespace. */ @@ -21,7 +22,8 @@ export const en: Record = { 'toggle.show': 'Show session panel', 'toggle.hide': 'Hide session panel', 'section.environment': 'Environment', - 'project.actions': 'Project directory actions', + 'project.label': 'Working folder', + 'project.actions': 'Working folder actions', } /** Japanese dictionary. */ @@ -30,7 +32,8 @@ export const ja = { 'toggle.show': 'セッションパネルを表示', 'toggle.hide': 'セッションパネルを非表示', 'section.environment': '環境', - 'project.actions': 'プロジェクトディレクトリの操作', + 'project.label': '作業フォルダー', + 'project.actions': '作業フォルダーの操作', } satisfies Record /** Spanish dictionary. */ @@ -39,7 +42,8 @@ export const es = { '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', + 'project.label': 'Carpeta de trabajo', + 'project.actions': 'Acciones de la carpeta de trabajo', } satisfies Record /** French dictionary. */ @@ -48,7 +52,8 @@ export const fr = { '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', + 'project.label': 'Dossier de travail', + 'project.actions': 'Actions sur le dossier de travail', } satisfies Record /** German dictionary. */ @@ -57,7 +62,8 @@ export const de = { 'toggle.show': 'Sitzungsbereich anzeigen', 'toggle.hide': 'Sitzungsbereich ausblenden', 'section.environment': 'Umgebung', - 'project.actions': 'Aktionen für das Projektverzeichnis', + 'project.label': 'Arbeitsordner', + 'project.actions': 'Aktionen für den Arbeitsordner', } satisfies Record /** Russian dictionary. */ @@ -66,7 +72,8 @@ export const ru = { 'toggle.show': 'Показать панель сеанса', 'toggle.hide': 'Скрыть панель сеанса', 'section.environment': 'Среда', - 'project.actions': 'Действия с каталогом проекта', + 'project.label': 'Рабочая папка', + 'project.actions': 'Действия с рабочей папкой', } satisfies Record /** Brazilian Portuguese dictionary. */ @@ -75,5 +82,6 @@ export const pt = { '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', + 'project.label': 'Pasta de trabalho', + 'project.actions': 'Ações da pasta de trabalho', } satisfies Record diff --git a/packages/client/ui-session-panel/tests/components.client.spec.tsx b/packages/client/ui-session-panel/tests/components.client.spec.tsx index 9d1d69967a..aee18c0db7 100644 --- a/packages/client/ui-session-panel/tests/components.client.spec.tsx +++ b/packages/client/ui-session-panel/tests/components.client.spec.tsx @@ -273,6 +273,7 @@ describe('EnvironmentSection', () => { describe('ProjectRow', () => { function rowProps(over: { + workingDirectory?: string | null workspacePath?: string cwd?: string home?: string @@ -280,6 +281,7 @@ describe('ProjectRow', () => { const renderFactorySlot = vi.fn((_name: string, input: { label: string }) => ) const props = { sessionId: SID, + useProjection: (key: string) => key === 'workingDirectory' ? over.workingDirectory : undefined, useWorkspaces: selectorOf({ items: over.workspacePath === undefined ? [] : [{ path: over.workspacePath, sessionIds: [SID] }], }), @@ -292,29 +294,48 @@ describe('ProjectRow', () => { return { props, renderFactorySlot, open } } - it('shows the listing Workspace directory with the home directory abbreviated', () => { + function folderOf(container: HTMLElement): { name: string | null; parent: string | null } { + const folder = container.querySelector('[data-session-panel-project] [tabindex="0"]') as HTMLElement + const [name, parent] = [...folder.children] + return { name: name?.textContent ?? null, parent: parent?.textContent ?? null } + } + + it('shows the working directory as its name and parent folder, with the label and full path in the tooltip', () => { const { props, renderFactorySlot } = rowProps({ - workspacePath: '/Users/me/projects/deepseek-harness', cwd: '/Users/me/elsewhere', home: '/Users/me', + workingDirectory: '/Users/me/projects/app/.worktrees/fix', + cwd: '/Users/me/projects/app', + workspacePath: '/Users/me/projects/app', + 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(folderOf(view.container)).toEqual({ name: 'fix', parent: '~/projects/app/.worktrees' }) + fireEvent.keyDown(document.body, { key: 'Tab' }) + fireEvent.focus(view.container.querySelector('[data-session-panel-project] [tabindex="0"]') as HTMLElement) + expect(screen.getByRole('tooltip', { hidden: true }).textContent).toBe('工作目录\n~/projects/app/.worktrees/fix') expect(renderFactorySlot).toHaveBeenCalledWith('contextMenu.button', expect.objectContaining({ - target: { kind: 'directory', value: { sessionId: SID, path: '/Users/me/projects/deepseek-harness' } }, - label: '项目目录操作', + target: { kind: 'directory', value: { sessionId: SID, path: '/Users/me/projects/app/.worktrees/fix' } }, + label: '工作目录操作', size: 'sm', })) - expect(screen.getByRole('button', { name: '项目目录操作' })).toBeTruthy() + 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 { props, open } = rowProps({ cwd: '/srv/app', workspacePath: '/srv' }) const view = render() - expect(view.container.querySelector('[data-path-label]')?.getAttribute('title')).toBe('/srv/app') + expect(folderOf(view.container)).toEqual({ name: 'app', parent: '/srv' }) 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('falls back to the listing Workspace when no directory is recorded, keeping a root parent and omitting an absent one', () => { + const atRoot = render() + expect(folderOf(atRoot.container)).toEqual({ name: 'srv', parent: '/' }) + atRoot.unmount() + const atHome = render() + expect(folderOf(atHome.container)).toEqual({ name: '~', parent: null }) + }) + it('renders nothing before the Session directory is known', () => { const { props } = rowProps({}) const view = render() diff --git a/packages/client/ui-session-panel/tsconfig.json b/packages/client/ui-session-panel/tsconfig.json index 1793f747f0..2b517b8c2d 100644 --- a/packages/client/ui-session-panel/tsconfig.json +++ b/packages/client/ui-session-panel/tsconfig.json @@ -53,6 +53,9 @@ { "path": "../../util/workspace-path" }, + { + "path": "../../session/working-directory" + }, { "path": "../../workspace/workspace" } diff --git a/packages/session/working-directory/README.i18n.yaml b/packages/session/working-directory/README.i18n.yaml index fd50066fe2..e718977c39 100644 --- a/packages/session/working-directory/README.i18n.yaml +++ b/packages/session/working-directory/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 87d7d2dbd7777429 /deepseek-ai-dsh-working-directory/use-this-package: - en: e65405026debde7c - zh: e12a648eb10ed16b + en: 4bb4eccf3b4b5f2f + zh: 41aae306e7fc82cf /deepseek-ai-dsh-working-directory/understand-the-implementation: en: f0458147d29631b1 zh: 6a288670dd084ffb diff --git a/packages/session/working-directory/README.md b/packages/session/working-directory/README.md index 44ed9ba9dc..fed67358e2 100644 --- a/packages/session/working-directory/README.md +++ b/packages/session/working-directory/README.md @@ -33,6 +33,8 @@ Mount alongside `fs`, `sessionProjections`, and `systemPrompt`. `defaultDirector ----- +Client programs that read the `workingDirectory` projection import its type declarations from `@deepseek-ai/dsh-working-directory/types`, which loads no runtime code. + Directory validation and publication delegate through `working-directory/access`, so the owner of a directory being removed can hold `ensure` and `set` into that directory until its operation settles. A listener waits only for an operation on the requested or current path, honours the request's `signal` while waiting, and otherwise calls `next()` at once; a rejection fails that access and leaves the recorded directory unchanged, with no fallback. Existing subprocesses keep their own directories. diff --git a/packages/session/working-directory/README.zh.md b/packages/session/working-directory/README.zh.md index 9561d73972..4d94a104a6 100644 --- a/packages/session/working-directory/README.zh.md +++ b/packages/session/working-directory/README.zh.md @@ -33,6 +33,8 @@ kind: "package-reference" ----- +读取 `workingDirectory` 投影的 Client 程序从 `@deepseek-ai/dsh-working-directory/types` 导入其类型声明,该入口不加载运行时代码。 + 目录验证与发布通过 `working-directory/access` 委派,使正在删除某目录的所有者可以阻塞进入该目录的 `ensure` 与 `set`,直到其操作结束。监听器只为请求路径或当前路径上的操作等待,等待时遵守请求的 `signal`,其余情况立即调用 `next()`;拒绝会使本次访问失败并保持记录的目录不变,不做回退。已有子进程保留各自的目录。 diff --git a/packages/session/working-directory/package.json b/packages/session/working-directory/package.json index e7433cb7ca..284ec9754e 100644 --- a/packages/session/working-directory/package.json +++ b/packages/session/working-directory/package.json @@ -18,6 +18,10 @@ "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, + "./types": { + "types": "./lib/types/types.d.ts", + "default": "./lib/types/types.js" + }, "./src/*": "./src/*", "./locale/*.json": "./locale/*.json", "./package.json": "./package.json" @@ -25,6 +29,7 @@ "files": [ "locale/*.json", "lib/index.js", + "lib/types/**/*.js", "lib/types/**/*.d.ts", "lib/types/**/*.d.ts.map", "lib/**/*.js.map", diff --git a/packages/session/working-directory/src/index.ts b/packages/session/working-directory/src/index.ts index 62c3750c2c..d9ff14ee92 100644 --- a/packages/session/working-directory/src/index.ts +++ b/packages/session/working-directory/src/index.ts @@ -13,6 +13,7 @@ import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { Session } from '@deepseek-ai/dsh-session' import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection' import type {} from '@deepseek-ai/dsh-system-prompt' +export type * from './types.ts' declare module '@deepseek-ai/cordis' { interface Events { @@ -56,13 +57,6 @@ declare module '@deepseek-ai/dsh-session/types' { } } -declare module '@deepseek-ai/dsh-session-projection/types' { - interface SessionProjectionMap { - /** Recorded current directory for Session observations, or null when none is recorded. */ - workingDirectory: string | null - } -} - /** Deployment default for Sessions without an original project directory. */ export interface Config { /** Absolute execution-world fallback directory; omitted values use the launch directory. */ diff --git a/packages/session/working-directory/src/types.ts b/packages/session/working-directory/src/types.ts new file mode 100644 index 0000000000..9801d3c092 --- /dev/null +++ b/packages/session/working-directory/src/types.ts @@ -0,0 +1,13 @@ +/** + * Import-free type declarations of the `workingDirectory` Session projection, for Client programs that read it. + * @module @deepseek-ai/dsh-working-directory/types + */ + +import type {} from '@deepseek-ai/dsh-session-projection/types' + +declare module '@deepseek-ai/dsh-session-projection/types' { + interface SessionProjectionMap { + /** Recorded current directory for Session observations, or null when none is recorded. */ + workingDirectory: string | null + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 20969ef056..518df7f8ea 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -5707,6 +5707,9 @@ importers: '@deepseek-ai/dsh-util-workspace-path': specifier: workspace:* version: link:../../util/workspace-path + '@deepseek-ai/dsh-working-directory': + specifier: workspace:* + version: link:../../session/working-directory '@deepseek-ai/dsh-workspace': specifier: workspace:* version: link:../../workspace/workspace From eaae69bcad4807e174abf02586ea06a42c3d238c Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 6 Nov 2026 17:32:03 +0800 Subject: [PATCH 040/404] fix(panel): hide the working folder's parent when too little of it fits --- .../ui-session-panel/src/client/ProjectRow.module.css | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/packages/client/ui-session-panel/src/client/ProjectRow.module.css b/packages/client/ui-session-panel/src/client/ProjectRow.module.css index fce60b0571..d0d430e14d 100644 --- a/packages/client/ui-session-panel/src/client/ProjectRow.module.css +++ b/packages/client/ui-session-panel/src/client/ProjectRow.module.css @@ -1,10 +1,14 @@ /* [name] · [parent]: the name keeps its width up to the row, and the parent - takes the remaining space and clips with an ellipsis. */ + fills the rest of the line and clips with an ellipsis. With less than 5em + left for it, the parent wraps onto a second line, which the one-line height + hides, so the row never shows a separator without a parent. */ .folder { display: flex; + flex-wrap: wrap; align-items: baseline; min-width: 0; + height: 1lh; overflow: hidden; white-space: nowrap; } @@ -17,13 +21,14 @@ .name { flex: 0 1 auto; min-width: 0; + max-width: 100%; overflow: hidden; text-overflow: ellipsis; } .parent { - flex: 0 1000 auto; - min-width: 0; + flex: 1 1 0; + min-width: 5em; overflow: hidden; color: var(--dsw-alias-label-tertiary); text-overflow: ellipsis; From 3b68abbcd4737da946f8b4dcfe033439222c3ead Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 6 Nov 2026 17:43:23 +0800 Subject: [PATCH 041/404] docs(panel): regenerate catalogs for the moved working directory declarations --- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index fbfbc16858..eedce85cda 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -4942,7 +4942,7 @@ export interface Config { ## `@deepseek-ai/dsh-working-directory` - `inject`: `fs` · `sessionProjections` · `systemPrompt` -- `source`: [`packages/session/working-directory/src/index.ts:67`](../packages/session/working-directory/src/index.ts) +- `source`: [`packages/session/working-directory/src/index.ts:61`](../packages/session/working-directory/src/index.ts) ```ts config-catalog /** Deployment default for Sessions without an original project directory. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index f7acfdf111..ab39103581 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -4944,7 +4944,7 @@ export interface Config { ## `@deepseek-ai/dsh-working-directory` - `inject`: `fs` · `sessionProjections` · `systemPrompt` -- `source`: [`packages/session/working-directory/src/index.ts:67`](../packages/session/working-directory/src/index.ts) +- `source`: [`packages/session/working-directory/src/index.ts:61`](../packages/session/working-directory/src/index.ts) ```ts config-catalog /** Deployment default for Sessions without an original project directory. */ diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index d6514e9585..1ebe4feeac 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -98,7 +98,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `workflow/log` | `emit` | [`packages/workflow/workflow/src/index.ts:58`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | | `workflow/phase` | `emit` | [`packages/workflow/workflow/src/index.ts:51`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | | `workflow/start` | `emit` | [`packages/workflow/workflow/src/index.ts:43`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | - | -| `working-directory/access` | `waterfall` | [`packages/session/working-directory/src/index.ts:29`](../packages/session/working-directory/src/index.ts) | [`working-directory`](../packages/session/working-directory) (`waterfall`) | `worktree` | +| `working-directory/access` | `waterfall` | [`packages/session/working-directory/src/index.ts:30`](../packages/session/working-directory/src/index.ts) | [`working-directory`](../packages/session/working-directory) (`waterfall`) | `worktree` | | `workspace/session-activity` | `waterfall` | [`packages/workspace/workspace/src/index.ts:129`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`waterfall`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) | | `workspace/session-archived` | `parallel` | [`packages/workspace/workspace/src/index.ts:156`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | `worktree` | | `workspace/session-stop` | `parallel` | [`packages/workspace/workspace/src/index.ts:147`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 38d90599f9..84e41cb79f 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -100,7 +100,7 @@ | `workflow/log` | `emit` | [`packages/workflow/workflow/src/index.ts:58`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | | `workflow/phase` | `emit` | [`packages/workflow/workflow/src/index.ts:51`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | | `workflow/start` | `emit` | [`packages/workflow/workflow/src/index.ts:43`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | - | -| `working-directory/access` | `waterfall` | [`packages/session/working-directory/src/index.ts:29`](../packages/session/working-directory/src/index.ts) | [`working-directory`](../packages/session/working-directory) (`waterfall`) | `worktree` | +| `working-directory/access` | `waterfall` | [`packages/session/working-directory/src/index.ts:30`](../packages/session/working-directory/src/index.ts) | [`working-directory`](../packages/session/working-directory) (`waterfall`) | `worktree` | | `workspace/session-activity` | `waterfall` | [`packages/workspace/workspace/src/index.ts:129`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`waterfall`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) | | `workspace/session-archived` | `parallel` | [`packages/workspace/workspace/src/index.ts:156`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | `worktree` | | `workspace/session-stop` | `parallel` | [`packages/workspace/workspace/src/index.ts:147`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) | From 53183d374cfbdebc25a2a11f12ca607347bc61e2 Mon Sep 17 00:00:00 2001 From: Yif <877193178@qq.com> Date: Fri, 6 Nov 2026 17:53:01 +0800 Subject: [PATCH 042/404] fix(ui): keep effort tag edge clicks out of the slider --- apps/web/tests/declared-reasoning.e2e.ts | 19 +++++++++++ .../src/client/EffortSlider.module.css | 32 ++++++++++--------- .../tests/effort-tag-drag.client.spec.tsx | 3 +- 3 files changed, 38 insertions(+), 16 deletions(-) diff --git a/apps/web/tests/declared-reasoning.e2e.ts b/apps/web/tests/declared-reasoning.e2e.ts index 4b804893b0..ebba03e46f 100644 --- a/apps/web/tests/declared-reasoning.e2e.ts +++ b/apps/web/tests/declared-reasoning.e2e.ts @@ -245,6 +245,25 @@ describe.skipIf(MODE === 'record').each([ const defaultHeight = await menu.evaluate(element => element.getBoundingClientRect().height) await menu.locator('[data-effort-label]').click() expect(await slider.inputValue()).toBe('0') + const tagHit = await menu.locator('[data-effort-tag]').evaluate((tag) => { + const caption = tag.querySelector('[data-effort-caption]')! + const bounds = tag.getBoundingClientRect() + const x = bounds.left + bounds.width / 2 + const y = bounds.bottom - 1 + return { + x, y, hitsCaption: document.elementFromPoint(x, y) === caption, + tagScrollWidth: tag.scrollWidth, tagClientWidth: tag.clientWidth, + captionScrollWidth: caption.scrollWidth, captionClientWidth: caption.clientWidth, + } + }) + expect(tagHit.hitsCaption).toBe(true) + await trigger.focus() + await page.mouse.click(tagHit.x, tagHit.y) + expect(await slider.inputValue()).toBe('0') + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + expect(requests).toBe(0) + expect(tagHit.tagScrollWidth).toBe(tagHit.tagClientWidth) + expect(tagHit.captionScrollWidth).toBe(tagHit.captionClientWidth) await info.click() const tooltip = page.getByRole('tooltip') await tooltip.waitFor() 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 b3b6e82a06..872b22df55 100644 --- a/packages/client/ui-model-selection/src/client/EffortSlider.module.css +++ b/packages/client/ui-model-selection/src/client/EffortSlider.module.css @@ -20,12 +20,15 @@ grid-row: 2; container-type: inline-size; position: relative; + z-index: 1; + pointer-events: none; height: 28px; margin: 8px 8px 0; } .value { position: absolute; + pointer-events: auto; top: 0; left: 0; width: max-content; @@ -33,15 +36,9 @@ translate: clamp(0px, calc(var(--effort-thumb-size) / 2 + (100cqw - var(--effort-thumb-size)) * var(--dsh-effort-position) - 50%), calc(100cqw - 100%)) 0; display: inline-flex; align-items: center; - gap: 4px; box-sizing: border-box; max-width: 100%; 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; - 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; @@ -53,20 +50,23 @@ user-select: none; } -.value:has(.infoButton) { - gap: 2px; - padding-inline-end: 1px; +.value:has(.infoButton) .caption { + padding-inline-end: 27px; } .caption { display: flex; flex: 1 1 auto; align-items: center; + box-sizing: border-box; min-width: 0; - height: 24px; - padding: 0; - border: 0; - background: transparent; + width: 100%; + 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; + background: color-mix(in srgb, var(--dsw-alias-state-business-primary) 8%, var(--dsw-alias-bg-module-platform)); color: inherit; font: inherit; white-space: inherit; @@ -79,7 +79,6 @@ .caption:focus-visible { outline: 2px solid currentColor; outline-offset: 1px; - border-radius: var(--dsw-radius-sm); } .caption[aria-disabled='true'] { @@ -113,8 +112,11 @@ } .infoButton { + position: absolute; + top: 2px; + right: 2px; + z-index: 1; display: inline-flex; - flex: 0 0 24px; align-items: center; justify-content: center; width: 24px; diff --git a/packages/client/ui-model-selection/tests/effort-tag-drag.client.spec.tsx b/packages/client/ui-model-selection/tests/effort-tag-drag.client.spec.tsx index 345d4bae3f..b39a361555 100644 --- a/packages/client/ui-model-selection/tests/effort-tag-drag.client.spec.tsx +++ b/packages/client/ui-model-selection/tests/effort-tag-drag.client.spec.tsx @@ -1,11 +1,12 @@ // @vitest-environment jsdom import { cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, expect, it, vi } from 'vitest' +import type { ComponentProps } from 'react' import { EffortSlider, type EffortSliderProps } from '../src/client/EffortSlider.tsx' afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals() }) -function setup(value: string | null = 'off', includeDefault = false, parentKey?: ReturnType) { +function setup(value: string | null = 'off', includeDefault = false, parentKey?: ComponentProps<'div'>['onKeyDown']) { vi.stubGlobal('matchMedia', (query: string) => ({ matches: query.includes('hover: hover'), media: query, onchange: null, addEventListener: vi.fn(), removeEventListener: vi.fn(), addListener: vi.fn(), removeListener: vi.fn(), dispatchEvent: () => true, From 7e14cfcd6a64b39e9a76f8461d9665ad637d2bc3 Mon Sep 17 00:00:00 2001 From: Yif <877193178@qq.com> Date: Fri, 6 Nov 2026 17:59:22 +0800 Subject: [PATCH 043/404] test(ui): wait for resized effort controls to become hittable --- apps/web/tests/declared-reasoning.e2e.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/web/tests/declared-reasoning.e2e.ts b/apps/web/tests/declared-reasoning.e2e.ts index ebba03e46f..0f12004a44 100644 --- a/apps/web/tests/declared-reasoning.e2e.ts +++ b/apps/web/tests/declared-reasoning.e2e.ts @@ -872,7 +872,7 @@ describe.skipIf(MODE === 'record').each([ 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 readLayout = () => info.evaluate((button) => { const tag = button.parentElement! const text = tag.querySelector('[data-effort-label]')! const name = text.querySelector('[data-effort-name]')! @@ -889,8 +889,9 @@ describe.skipIf(MODE === 'record').each([ 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', + await expect.poll(readLayout).toMatchObject({ width: 24, height: 24, clipped: false, ellipsis: 'ellipsis', nameText: 'Predeterminado', nameFits: true, nameVisible: true, contained: true, reachable: true }) + const layout = await readLayout() expect(layout.textWidth).toBeGreaterThan(0) expect(layout.textGap).toBeCloseTo(2, 1) expect(layout.endInset).toBeCloseTo(2, 1) From fda29f726da9c2d23269d4a3638eef296a830f61 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 6 Nov 2026 18:02:08 +0800 Subject: [PATCH 044/404] fix(user-questions): keep the answerer's message in PROVIDER_ERROR Wrapping a non-HarnessError answerer failure replaced its message with a generic sentence, so callers and the model lost the concrete reason, such as a closed connection. The PROVIDER_ERROR wrapper now keeps the original message and falls back to the generic sentence only for a value that is not an Error. Refs #7869 --- docs/subsystems/user-questions.i18n.yaml | 4 ++-- docs/subsystems/user-questions.md | 9 +++++---- docs/subsystems/user-questions.zh.md | 9 +++++---- packages/interaction/user-questions/src/index.ts | 10 ++++++---- .../user-questions/tests/user-questions.spec.ts | 12 ++++++------ packages/plan/plan-mode/tests/plan-mode.spec.ts | 2 +- 6 files changed, 25 insertions(+), 21 deletions(-) diff --git a/docs/subsystems/user-questions.i18n.yaml b/docs/subsystems/user-questions.i18n.yaml index bacd251ef1..483df1b1a4 100644 --- a/docs/subsystems/user-questions.i18n.yaml +++ b/docs/subsystems/user-questions.i18n.yaml @@ -24,5 +24,5 @@ en: 74fa698d4a115e80 zh: 4e9b03b5eab2ae5e /user-interaction/errors: - en: eb0a4f94282f8c18 - zh: 92c41869431b120e + en: 832b165cfa48839d + zh: 6989f734b373c1f9 diff --git a/docs/subsystems/user-questions.md b/docs/subsystems/user-questions.md index c87fe49f14..daf0db242a 100644 --- a/docs/subsystems/user-questions.md +++ b/docs/subsystems/user-questions.md @@ -209,7 +209,7 @@ After a Host restart, the Remote layer resumes the root agent when the Session r ## Errors -`UserQuestionError` extends `HarnessError`, so `ctx.tools.execute()` preserves `{ name, code }` for model-facing tool failures such as `EMPTY_QUESTIONS`, `BAD_INTENT`, `NO_PROVIDER`, `ASK_ABORTED`, or UI-side cancellation. An answerer failure that is not a `HarnessError` becomes `PROVIDER_ERROR` with the original as `cause`; another `HarnessError` keeps its own `name` and `code`. +`UserQuestionError` extends `HarnessError`, so `ctx.tools.execute()` preserves `{ name, code }` for model-facing tool failures such as `EMPTY_QUESTIONS`, `BAD_INTENT`, `NO_PROVIDER`, `ASK_ABORTED`, or UI-side cancellation. An answerer failure that is not a `HarnessError` becomes `PROVIDER_ERROR` with the original message and the original as `cause`; another `HarnessError` keeps its own `name` and `code`. ```ts type-equiv /** Stable error taxonomy for user-questions failures. */ @@ -287,9 +287,10 @@ async askTimed( request: AskUserQuestionRequest & { agent: Agent }, callId: Tool * @throws {UserQuestionError} code `ASK_ABORTED` when the supplied signal * is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent * is not the registry's exact live instance, `DELEGATED_CALLER` when - * that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer - * fails with a value that is not a `HarnessError`; a coded `HarnessError` - * from an answerer keeps its `name` and `code`. + * that live agent has subagent origin, or `PROVIDER_ERROR`, keeping the + * original message, when an answerer fails with a value that is not a + * `HarnessError`; a coded `HarnessError` from an answerer keeps its `name` + * and `code`. */ async ask(request: AskUserQuestionRequest): Promise ``` diff --git a/docs/subsystems/user-questions.zh.md b/docs/subsystems/user-questions.zh.md index 4dc465f750..aeb1818584 100644 --- a/docs/subsystems/user-questions.zh.md +++ b/docs/subsystems/user-questions.zh.md @@ -209,7 +209,7 @@ Host 重启后,Session 重开时 Remote 层会恢复根 agent。之后的迟 ## 错误 -`UserQuestionError` 继承 `HarnessError`,因此 `ctx.tools.execute()` 会保留 `{ name, code }`,用于面向模型的工具失败,如 `EMPTY_QUESTIONS`、`BAD_INTENT`、`NO_PROVIDER`、`ASK_ABORTED` 或 UI 侧取消。不是 `HarnessError` 的应答方失败会变为 `PROVIDER_ERROR`,原错误作为 `cause`;其他 `HarnessError` 保留自身的 `name` 与 `code`。 +`UserQuestionError` 继承 `HarnessError`,因此 `ctx.tools.execute()` 会保留 `{ name, code }`,用于面向模型的工具失败,如 `EMPTY_QUESTIONS`、`BAD_INTENT`、`NO_PROVIDER`、`ASK_ABORTED` 或 UI 侧取消。不是 `HarnessError` 的应答方失败会变为 `PROVIDER_ERROR`,保留原 message,原错误作为 `cause`;其他 `HarnessError` 保留自身的 `name` 与 `code`。 ```ts type-equiv /** Stable error taxonomy for user-questions failures. */ @@ -287,9 +287,10 @@ async askTimed( request: AskUserQuestionRequest & { agent: Agent }, callId: Tool * @throws {UserQuestionError} code `ASK_ABORTED` when the supplied signal * is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent * is not the registry's exact live instance, `DELEGATED_CALLER` when - * that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer - * fails with a value that is not a `HarnessError`; a coded `HarnessError` - * from an answerer keeps its `name` and `code`. + * that live agent has subagent origin, or `PROVIDER_ERROR`, keeping the + * original message, when an answerer fails with a value that is not a + * `HarnessError`; a coded `HarnessError` from an answerer keeps its `name` + * and `code`. */ async ask(request: AskUserQuestionRequest): Promise ``` diff --git a/packages/interaction/user-questions/src/index.ts b/packages/interaction/user-questions/src/index.ts index 0242301291..5c850eeb54 100644 --- a/packages/interaction/user-questions/src/index.ts +++ b/packages/interaction/user-questions/src/index.ts @@ -286,9 +286,10 @@ export class UserQuestionService extends TypertRemoteService { * @throws {UserQuestionError} code `ASK_ABORTED` when the supplied signal * is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent * is not the registry's exact live instance, `DELEGATED_CALLER` when - * that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer - * fails with a value that is not a `HarnessError`; a coded `HarnessError` - * from an answerer keeps its `name` and `code`. + * that live agent has subagent origin, or `PROVIDER_ERROR`, keeping the + * original message, when an answerer fails with a value that is not a + * `HarnessError`; a coded `HarnessError` from an answerer keeps its `name` + * and `code`. */ async ask(request: AskUserQuestionRequest): Promise { if (request.signal?.aborted) { @@ -359,7 +360,8 @@ export class UserQuestionService extends TypertRemoteService { throw abortedQuestion(error) } if (restored instanceof HarnessError) throw restored - throw new UserQuestionError('the user-questions answerer failed before the user answered', 'PROVIDER_ERROR', { cause: error }) + const message = error instanceof Error ? error.message : 'the user-questions answerer failed before the user answered' + throw new UserQuestionError(message, 'PROVIDER_ERROR', { cause: error }) } } } diff --git a/packages/interaction/user-questions/tests/user-questions.spec.ts b/packages/interaction/user-questions/tests/user-questions.spec.ts index a4f3208de1..09a32fd961 100644 --- a/packages/interaction/user-questions/tests/user-questions.spec.ts +++ b/packages/interaction/user-questions/tests/user-questions.spec.ts @@ -174,12 +174,12 @@ describe('UserQuestionService', () => { }) it.each([ - ['an ordinary Error', new Error('provider failed')], + ['an ordinary Error', new Error('provider failed'), 'provider failed'], ['a namesake Error without a string code', Object.assign(new Error('provider failed'), { name: 'UserQuestionError', - })], - ['a non-Error rejection', { name: 'UserQuestionError', code: 'ASK_CANCELLED' }], - ])('classifies %s from the provider as PROVIDER_ERROR', async (_label, rejection) => { + }), 'provider failed'], + ['a non-Error rejection', { name: 'UserQuestionError', code: 'ASK_CANCELLED' }, 'the user-questions answerer failed before the user answered'], + ])('classifies %s from the provider as PROVIDER_ERROR', async (_label, rejection, message) => { const ctx = new Context() await ctx.plugin(UserQuestionService) registerAnswerer(ctx, { ask: vi.fn().mockRejectedValue(rejection) }) @@ -188,7 +188,7 @@ describe('UserQuestionService', () => { questions: [{ id: 'confirm', question: 'Proceed?' }], }).then(() => undefined, (error: unknown) => error) expect(failure).toBeInstanceOf(UserQuestionError) - expect(failure).toMatchObject({ name: 'UserQuestionError', code: 'PROVIDER_ERROR', cause: rejection }) + expect(failure).toMatchObject({ name: 'UserQuestionError', code: 'PROVIDER_ERROR', message, cause: rejection }) }) it('rejects empty question batches before reaching the provider', async () => { @@ -579,7 +579,7 @@ describe('askTimed', () => { registerAnswerer(ctx, { ask: () => Promise.reject(crash) }) await expect(ctx.userQuestions.askTimed({ agent, questions: timedQuestions }, timedCallId, 120_000)) - .rejects.toMatchObject({ name: 'UserQuestionError', code: 'PROVIDER_ERROR', cause: crash }) + .rejects.toMatchObject({ name: 'UserQuestionError', code: 'PROVIDER_ERROR', message: 'provider crashed', cause: crash }) await ctx.fiber.dispose() }) diff --git a/packages/plan/plan-mode/tests/plan-mode.spec.ts b/packages/plan/plan-mode/tests/plan-mode.spec.ts index 0ebe17cb31..b65e283886 100644 --- a/packages/plan/plan-mode/tests/plan-mode.spec.ts +++ b/packages/plan/plan-mode/tests/plan-mode.spec.ts @@ -1177,7 +1177,7 @@ describe('exit_plan_mode', () => { registerQuestionAnswerer(ctx, { ask: () => { throw new Error('review aborted') } }) const result = await callExit(ctx, agent) expect(result.isError).toBe(true) - expect(result.content).toEqual([{ type: 'text', text: 'Error: the user-questions answerer failed before the user answered' }]) + expect(result.content).toEqual([{ type: 'text', text: 'Error: review aborted' }]) expect(result.error?.info).toEqual({ name: 'UserQuestionError', code: 'PROVIDER_ERROR' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) From 1440cf2fb97b6f393ae526a479958d631dcefaf6 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 6 Nov 2026 18:02:10 +0800 Subject: [PATCH 045/404] test(subagent-dsh-sdk): expect ToolArgsError for effort-only delegation An effort-only route request now fails as ToolArgsError, whose message carries the "invalid arguments:" prefix; the production-profile e2e asserts that text and the recorded INVALID_ARGS identity. Refs #7869 --- .../subagent/subagent-dsh-sdk/tests/loader-composition.e2e.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/subagent/subagent-dsh-sdk/tests/loader-composition.e2e.ts b/packages/subagent/subagent-dsh-sdk/tests/loader-composition.e2e.ts index b6d6e3d03f..bf7d3e394f 100644 --- a/packages/subagent/subagent-dsh-sdk/tests/loader-composition.e2e.ts +++ b/packages/subagent/subagent-dsh-sdk/tests/loader-composition.e2e.ts @@ -157,8 +157,9 @@ describe('SDK subagent routing and diagnostics through the production profile', expect(results[0]!.data.message.isError).toBe(true) expect(results[0]!.data.message.content).toEqual([{ type: 'text', - text: 'Error: child LLM `reasoning_effort` requires both `provider` and `model`; supply both or omit all three fields', + text: 'Error: invalid arguments: child LLM `reasoning_effort` requires both `provider` and `model`; supply both or omit all three fields', }]) + expect(results[0]!.data.error).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) expect(events.some(event => event.type === 'subagent/catalog')).toBe(false) expect(existsSync(join(child.childHome, 'sessions'))).toBe(false) }, From de273ffe2d57d69dcd1aa327d8525421e00eab3d Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 6 Nov 2026 18:02:11 +0800 Subject: [PATCH 046/404] feat(typert): make RemoteError a HarnessError RemoteError extended plain Error because dsh-llm, which owned HarnessError, depends on dsh-typert-protocol. With HarnessError in the dependency-free dsh-error package, RemoteError now extends it and keeps its name, Remote code, details, and constructor, so a tool body that throws one records name RemoteError and its code on tool/result. An unknown or unloadable delegation preset therefore keeps the registry's agent-preset/not-found or agent-preset/invalid identity, and the subagent runtime no longer rewraps it as PRESET_UNAVAILABLE. Client bundles inline dsh-error with the protocol layer; no client code depends on HarnessError identity. Refs #7869 --- ...28-ctx-remote-failure-vocabulary.i18n.yaml | 4 ++-- ...026-08-28-ctx-remote-failure-vocabulary.md | 6 +++--- ...-08-28-ctx-remote-failure-vocabulary.zh.md | 6 +++--- docs/module-graph.md | 7 ++++--- docs/module-graph.zh.md | 7 ++++--- packages/client/tsdown.client.ts | 2 +- .../extensions/tool-cordis/src/api-catalog.ts | 8 ++++++-- packages/subagent/subagent/README.i18n.yaml | 4 ++-- packages/subagent/subagent/README.md | 2 +- packages/subagent/subagent/README.zh.md | 2 +- packages/subagent/subagent/package.json | 1 + packages/subagent/subagent/src/child-agent.ts | 14 ++++--------- .../tests/continuation-presets.spec.ts | 15 +++++--------- .../tests/preset-selection.spec.ts | 6 +++--- packages/typert/protocol/README.i18n.yaml | 4 ++-- packages/typert/protocol/README.md | 2 +- packages/typert/protocol/README.zh.md | 2 +- packages/typert/protocol/package.json | 6 ++++-- packages/typert/protocol/src/remote-error.ts | 12 ++++++----- .../protocol/tests/remote-error.spec.ts | 20 +++++++++++++++++++ packages/typert/protocol/tsconfig.json | 3 +++ pnpm-lock.yaml | 6 ++++++ 22 files changed, 84 insertions(+), 55 deletions(-) create mode 100644 packages/typert/protocol/tests/remote-error.spec.ts diff --git a/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.i18n.yaml index 2e76fba547..2589183c49 100644 --- a/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.i18n.yaml @@ -9,8 +9,8 @@ en: 990d46f713fb6303 zh: 592cd6128a9640b1 /agent-note-one-remote-failure-vocabulary-for-ctx-remote/decision: - en: 120e2fb97ac765d8 - zh: 5d5f110db4a9b717 + en: b54b9d98a34eeaa1 + zh: ac8e3d493b554c2d /agent-note-one-remote-failure-vocabulary-for-ctx-remote/code-ownership: en: cc1d8b88f7349b77 zh: 70f010e3310e2667 diff --git a/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.md b/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.md index 7238ae23b4..146a359889 100644 --- a/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.md +++ b/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.md @@ -16,12 +16,12 @@ Fixed Host facts bypassed `ctx.remote` too: the Host home came from `(ctx.get('c ## Decision -`@deepseek-ai/dsh-typert-protocol` exports one failure class, `RemoteError`: a real `Error` carrying readonly `code` and `details`, the structural marker `isDSHRemoteError`, and standard `ErrorOptions` (`cause` holds in-process only). The correspondence between codes and details lives in one merge-extensible `RemoteErrorDetailsMap`; `RemoteFailure` is the code-distributed union of instances, and `RemoteResult` keeps its shape. +`@deepseek-ai/dsh-typert-protocol` exports one failure class, `RemoteError`: a `HarnessError` from the dependency-free `@deepseek-ai/dsh-error` carrying readonly `code` and `details`, the structural marker `isDSHRemoteError`, and standard `ErrorOptions` (`cause` holds in-process only). The correspondence between codes and details lives in one merge-extensible `RemoteErrorDetailsMap`; `RemoteFailure` is the code-distributed union of instances, and `RemoteResult` keeps its shape. ```text -export class RemoteError extends Error { +export class RemoteError extends HarnessError { readonly isDSHRemoteError: true = true - constructor(readonly code: Code, message: string, + constructor(override readonly code: Code, message: string, readonly details: RemoteErrorDetailsMap[Code], options?: ErrorOptions) } export type RemoteFailure = { [C in RemoteErrorCode]: RemoteError }[RemoteErrorCode] diff --git a/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.zh.md b/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.zh.md index db0b2969bc..12b2ad4f8e 100644 --- a/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.zh.md @@ -16,12 +16,12 @@ Host 固定事实同样绕过了 `ctx.remote`:Host home 取自 `(ctx.get('conn ## Decision -`@deepseek-ai/dsh-typert-protocol` 导出唯一的失败类 `RemoteError`:一个真 `Error`,带只读 `code` 与 `details`、结构标记 `isDSHRemoteError`,以及标准 `ErrorOptions`(`cause` 只在进程内有效)。码与 details 的对应关系收进一张 merge-extensible 的 `RemoteErrorDetailsMap`;`RemoteFailure` 是按码分布的实例 union,`RemoteResult` 形状不变。 +`@deepseek-ai/dsh-typert-protocol` 导出唯一的失败类 `RemoteError`:一个继承无依赖包 `@deepseek-ai/dsh-error` 中 `HarnessError` 的错误,带只读 `code` 与 `details`、结构标记 `isDSHRemoteError`,以及标准 `ErrorOptions`(`cause` 只在进程内有效)。码与 details 的对应关系收进一张 merge-extensible 的 `RemoteErrorDetailsMap`;`RemoteFailure` 是按码分布的实例 union,`RemoteResult` 形状不变。 ```text -export class RemoteError extends Error { +export class RemoteError extends HarnessError { readonly isDSHRemoteError: true = true - constructor(readonly code: Code, message: string, + constructor(override readonly code: Code, message: string, readonly details: RemoteErrorDetailsMap[Code], options?: ErrorOptions) } export type RemoteFailure = { [C in RemoteErrorCode]: RemoteError }[RemoteErrorCode] diff --git a/docs/module-graph.md b/docs/module-graph.md index 6913c9fca6..ef941e1c54 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -506,8 +506,8 @@ flowchart TD pkg_storage_json --> pkg_storage pkg_storage_sqlite --> pkg_storage pkg_subprocess --> pkg_http_proxy - pkg_remote_mock --> pkg_typert_protocol pkg_typert_loader --> pkg_typert_registry + pkg_typert_protocol --> pkg_error pkg_system_prompt --> pkg_llm pkg_system_prompt --> pkg_scope pkg_skill --> pkg_llm @@ -553,6 +553,7 @@ flowchart TD pkg_subprocess_local --> pkg_subprocess pkg_subprocess_local --> pkg_timeout pkg_otel --> pkg_session + pkg_remote_mock --> pkg_typert_protocol pkg_session_snapshot --> pkg_http_proxy pkg_session_snapshot --> pkg_session pkg_fs --> pkg_brand @@ -1687,7 +1688,6 @@ flowchart TD | [`win32-process`](../packages/subprocess/win32-process) | `subprocess` | — | | [`llm-mock-server`](../packages/test-support/llm-mock-server) | `test-support` | — | | [`typert-generator`](../packages/typert/generator) | `typert` | — | -| [`typert-protocol`](../packages/typert/protocol) | `typert` | — | | [`typert-registry`](../packages/typert/registry) | `typert` | — | | [`llm`](../packages/llm/llm) | `llm` | [`error`](../packages/util/error) | | [`session`](../packages/core/session) | `core` | [`scope`](../packages/core/scope) | @@ -1704,8 +1704,8 @@ flowchart TD | [`storage-json`](../packages/storage/storage-json) | `storage` | [`storage`](../packages/storage/storage) | | [`storage-sqlite`](../packages/storage/storage-sqlite) | `storage` | [`storage`](../packages/storage/storage) | | [`subprocess`](../packages/subprocess/subprocess) | `subprocess` | [`http-proxy`](../packages/util/http-proxy) | -| [`remote-mock`](../packages/test-support/remote-mock) | `test-support` | [`typert-protocol`](../packages/typert/protocol) | | [`typert-loader`](../packages/typert/loader) | `typert` | [`typert-registry`](../packages/typert/registry) | +| [`typert-protocol`](../packages/typert/protocol) | `typert` | [`error`](../packages/util/error) | | [`system-prompt`](../packages/core/system-prompt) | `core` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | | [`skill`](../packages/skill/skill) | `skill` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | | [`web`](../packages/web/web) | `web` | [`llm`](../packages/llm/llm) | @@ -1728,6 +1728,7 @@ flowchart TD | [`settings`](../packages/settings/settings) | `settings` | [`brand`](../packages/util/brand), [`session`](../packages/core/session) | | [`subprocess-local`](../packages/subprocess/subprocess-local) | `subprocess` | [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`otel`](../packages/telemetry/otel) | `telemetry` | [`session`](../packages/core/session) | +| [`remote-mock`](../packages/test-support/remote-mock) | `test-support` | [`typert-protocol`](../packages/typert/protocol) | | [`session-snapshot`](../packages/test-support/session-snapshot) | `test-support` | [`http-proxy`](../packages/util/http-proxy), [`session`](../packages/core/session) | | [`fs`](../packages/fs/fs) | `fs` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | | [`skill-office`](../packages/skill/skill-office) | `skill` | [`skill`](../packages/skill/skill) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index aa668a72c2..ff50815bc6 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -508,8 +508,8 @@ flowchart TD pkg_storage_json --> pkg_storage pkg_storage_sqlite --> pkg_storage pkg_subprocess --> pkg_http_proxy - pkg_remote_mock --> pkg_typert_protocol pkg_typert_loader --> pkg_typert_registry + pkg_typert_protocol --> pkg_error pkg_system_prompt --> pkg_llm pkg_system_prompt --> pkg_scope pkg_skill --> pkg_llm @@ -555,6 +555,7 @@ flowchart TD pkg_subprocess_local --> pkg_subprocess pkg_subprocess_local --> pkg_timeout pkg_otel --> pkg_session + pkg_remote_mock --> pkg_typert_protocol pkg_session_snapshot --> pkg_http_proxy pkg_session_snapshot --> pkg_session pkg_fs --> pkg_brand @@ -1689,7 +1690,6 @@ flowchart TD | [`win32-process`](../packages/subprocess/win32-process) | `subprocess` | — | | [`llm-mock-server`](../packages/test-support/llm-mock-server) | `test-support` | — | | [`typert-generator`](../packages/typert/generator) | `typert` | — | -| [`typert-protocol`](../packages/typert/protocol) | `typert` | — | | [`typert-registry`](../packages/typert/registry) | `typert` | — | | [`llm`](../packages/llm/llm) | `llm` | [`error`](../packages/util/error) | | [`session`](../packages/core/session) | `core` | [`scope`](../packages/core/scope) | @@ -1706,8 +1706,8 @@ flowchart TD | [`storage-json`](../packages/storage/storage-json) | `storage` | [`storage`](../packages/storage/storage) | | [`storage-sqlite`](../packages/storage/storage-sqlite) | `storage` | [`storage`](../packages/storage/storage) | | [`subprocess`](../packages/subprocess/subprocess) | `subprocess` | [`http-proxy`](../packages/util/http-proxy) | -| [`remote-mock`](../packages/test-support/remote-mock) | `test-support` | [`typert-protocol`](../packages/typert/protocol) | | [`typert-loader`](../packages/typert/loader) | `typert` | [`typert-registry`](../packages/typert/registry) | +| [`typert-protocol`](../packages/typert/protocol) | `typert` | [`error`](../packages/util/error) | | [`system-prompt`](../packages/core/system-prompt) | `core` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | | [`skill`](../packages/skill/skill) | `skill` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | | [`web`](../packages/web/web) | `web` | [`llm`](../packages/llm/llm) | @@ -1730,6 +1730,7 @@ flowchart TD | [`settings`](../packages/settings/settings) | `settings` | [`brand`](../packages/util/brand), [`session`](../packages/core/session) | | [`subprocess-local`](../packages/subprocess/subprocess-local) | `subprocess` | [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`otel`](../packages/telemetry/otel) | `telemetry` | [`session`](../packages/core/session) | +| [`remote-mock`](../packages/test-support/remote-mock) | `test-support` | [`typert-protocol`](../packages/typert/protocol) | | [`session-snapshot`](../packages/test-support/session-snapshot) | `test-support` | [`http-proxy`](../packages/util/http-proxy), [`session`](../packages/core/session) | | [`fs`](../packages/fs/fs) | `fs` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | | [`skill-office`](../packages/skill/skill-office) | `skill` | [`skill`](../packages/skill/skill) | diff --git a/packages/client/tsdown.client.ts b/packages/client/tsdown.client.ts index 7df6b6f529..592b634dfb 100644 --- a/packages/client/tsdown.client.ts +++ b/packages/client/tsdown.client.ts @@ -82,7 +82,7 @@ function styleInjectionModule( * Everything else under @deepseek-ai/* is either a module-table entry * (external) or a leak the purity gate rejects. */ -export const INLINE_SAFE = /^(?:@deepseek-ai\/dsh-(?:file-reference|fs-patch|session|llm|tools|brand|official-bundles|deque|output-retention|typert-protocol|util-crypto|util-time|util-values|util-workspace-path)(?:\/|$)|@deepseek-ai\/dsh-util-file-drag$|@deepseek-ai\/dsh-token-meter\/client$|@deepseek-ai\/dsh-commands\/builtin$|@deepseek-ai\/dsh-native-command\/types$|@deepseek-ai\/dsh-host-open-in-app\/shared$|@deepseek-ai\/dsh-plugin-manager\/registry$|@deepseek-ai\/dsh-agent-preset-registry\/display$|@deepseek-ai\/dsh-api-workspace-controller\/default-workspace$|@deepseek-ai\/dsh-spill-policy\/notice$)/ +export const INLINE_SAFE = /^(?:@deepseek-ai\/dsh-(?:file-reference|fs-patch|session|llm|tools|brand|error|official-bundles|deque|output-retention|typert-protocol|util-crypto|util-time|util-values|util-workspace-path)(?:\/|$)|@deepseek-ai\/dsh-util-file-drag$|@deepseek-ai\/dsh-token-meter\/client$|@deepseek-ai\/dsh-commands\/builtin$|@deepseek-ai\/dsh-native-command\/types$|@deepseek-ai\/dsh-host-open-in-app\/shared$|@deepseek-ai\/dsh-plugin-manager\/registry$|@deepseek-ai\/dsh-agent-preset-registry\/display$|@deepseek-ai\/dsh-api-workspace-controller\/default-workspace$|@deepseek-ai\/dsh-spill-policy\/notice$)/ /** * Vendored framework libraries: rescoped into @deepseek-ai, so the gate below diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 199ff2c9a5..4b650a2362 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -4369,7 +4369,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ description: 'Ask the scoped answerer waterfall and wait for the user\'s answer.\n\nWhen a caller supplies an agent, human interaction is valid only for the exact live instance of an ordinary Session. Explicit subagent origin rejects delegated callers; historical ordinary forks may retain parent metadata and still ask normally.', parameters: [{ name: 'request', description: 'Questions, owner agent, and abort signal.' }], returns: 'The answer chosen or typed by the human.', - throws: ['{UserQuestionError} code `ASK_ABORTED` when the supplied signal is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent is not the registry\'s exact live instance, `DELEGATED_CALLER` when that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer fails with a value that is not a `HarnessError`; a coded `HarnessError` from an answerer keeps its `name` and `code`.'], + throws: ['{UserQuestionError} code `ASK_ABORTED` when the supplied signal is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent is not the registry\'s exact live instance, `DELEGATED_CALLER` when that live agent has subagent origin, or `PROVIDER_ERROR`, keeping the original message, when an answerer fails with a value that is not a `HarnessError`; a coded `HarnessError` from an answerer keeps its `name` and `code`.'], }, ], }, @@ -6802,6 +6802,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'GrantRecord', declaration: 'export interface GrantRecord {\n readonly kind: \'grant\';\n readonly payload: unknown;\n}', }, + { + name: 'HarnessError', + declaration: 'export class HarnessError extends Error {\n readonly code: string;\n constructor(message: string, code: string, options?: ErrorOptions);\n}', + }, { name: 'HookBudget', declaration: 'export interface HookBudget {\n readonly ms: number;\n readonly remainingMs: number;\n}', @@ -8132,7 +8136,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'RemoteError', - declaration: 'export class RemoteError extends Error {\n readonly isDSHRemoteError: true;\n constructor(readonly code: Code, message: string, readonly details: RemoteErrorDetailsMap[Code], options?: ErrorOptions);\n}', + declaration: 'export class RemoteError extends HarnessError {\n readonly isDSHRemoteError: true;\n constructor(override readonly code: Code, message: string, readonly details: RemoteErrorDetailsMap[Code], options?: ErrorOptions);\n}', }, { name: 'RemoteErrorCode', diff --git a/packages/subagent/subagent/README.i18n.yaml b/packages/subagent/subagent/README.i18n.yaml index d89a9ce18b..01bc38e2e5 100644 --- a/packages/subagent/subagent/README.i18n.yaml +++ b/packages/subagent/subagent/README.i18n.yaml @@ -39,8 +39,8 @@ en: bf3175c2218a16dd zh: 4be9271efe71ddb7 /deepseek-ai-dsh-subagent/use-this-package/failure-and-recovery: - en: bdb3204a71ee2a8f - zh: 74d7d4e9eca20e2a + en: 4815c56bfcb844e9 + zh: 424c6133c4805a66 /deepseek-ai-dsh-subagent/understand-the-implementation: en: 74d91b364b23f88d zh: 19cc558105efe8df diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index 916c73346e..6cac06daba 100644 --- a/packages/subagent/subagent/README.md +++ b/packages/subagent/subagent/README.md @@ -79,7 +79,7 @@ In-process spawn accepts an independent `agentPreset`; fork and external backend ### Failure and recovery -Starting without the `agents` service rejects with `CONTINUATION_UNAVAILABLE`; an available runtime rejects a missing or replaced parent with `UNAUTHORIZED`. Providers implementing neither execution method are rejected at registration with `UNSUPPORTED_CAPABILITY`; unsupported requested capabilities reject creation with the same code. If a provider is removed or replaced while directory resolution is pending, creation rejects with `PROVIDER_CHANGED` before invoking either provider; retry the delegation against the current registration. Every creation failure below is a `SubagentError`: a child beyond the requested depth rejects with the `SubagentDepthError` subclass and `DEPTH_EXCEEDED`, an invalid runtime `subagentDepth` with `INVALID_DEPTH`, a fresh child whose selected preset is unknown or cannot load, or that cannot join its creator's preset revision, with `PRESET_UNAVAILABLE`, a local child without the working-directory service with `WORKING_DIRECTORY_UNAVAILABLE`, and an out-of-process child whose cwd is relative or not enterable with `INVALID_CWD`. A cold target whose persisted descriptor is corrupt rejects with `NOT_RESUMABLE`, and `structured_output` called while input is pending fails with `STRUCTURED_OUTPUT_PENDING_INPUT`. The caller signal cancels only unpublished work; after publication, `dispose()` cancels the exact activation and waits for its resource cleanup. Creation descendants continue independently; hosts must await `drainDescendants([root])` before disposing the root handle to stop all members and await pending startup. `result` settles after teardown and notifications, carrying output, optional structured data, and a stop reason; capture failures reject it after teardown. Cleanup failures reject `dispose()` and mark the lifecycle end as failed; the result promise and parent notification retain the captured execution result. +Starting without the `agents` service rejects with `CONTINUATION_UNAVAILABLE`; an available runtime rejects a missing or replaced parent with `UNAUTHORIZED`. Providers implementing neither execution method are rejected at registration with `UNSUPPORTED_CAPABILITY`; unsupported requested capabilities reject creation with the same code. If a provider is removed or replaced while directory resolution is pending, creation rejects with `PROVIDER_CHANGED` before invoking either provider; retry the delegation against the current registration. Every creation failure below is a `SubagentError`: a child beyond the requested depth rejects with the `SubagentDepthError` subclass and `DEPTH_EXCEEDED`, an invalid runtime `subagentDepth` with `INVALID_DEPTH`, a child that cannot join its creator's preset revision with `PRESET_UNAVAILABLE` (an unknown or unloadable selected preset keeps the registry's `RemoteError` code), a local child without the working-directory service with `WORKING_DIRECTORY_UNAVAILABLE`, and an out-of-process child whose cwd is relative or not enterable with `INVALID_CWD`. A cold target whose persisted descriptor is corrupt rejects with `NOT_RESUMABLE`, and `structured_output` called while input is pending fails with `STRUCTURED_OUTPUT_PENDING_INPUT`. The caller signal cancels only unpublished work; after publication, `dispose()` cancels the exact activation and waits for its resource cleanup. Creation descendants continue independently; hosts must await `drainDescendants([root])` before disposing the root handle to stop all members and await pending startup. `result` settles after teardown and notifications, carrying output, optional structured data, and a stop reason; capture failures reject it after teardown. Cleanup failures reject `dispose()` and mark the lifecycle end as failed; the result promise and parent notification retain the captured execution result. ----- diff --git a/packages/subagent/subagent/README.zh.md b/packages/subagent/subagent/README.zh.md index 8cc7e6bda9..1e8dbb6355 100644 --- a/packages/subagent/subagent/README.zh.md +++ b/packages/subagent/subagent/README.zh.md @@ -79,7 +79,7 @@ kind: "package-reference" ### 失败与恢复 -缺少 `agents` 服务时,启动请求以 `CONTINUATION_UNAVAILABLE` 拒绝;运行时可用但父级缺失或被替换时,以 `UNAUTHORIZED` 拒绝。未实现任何执行方法的提供方会在注册时以 `UNSUPPORTED_CAPABILITY` 被拒绝;请求不受支持的能力会以同一码使创建失败。如果等待目录解析期间提供方被移除或替换,创建会在调用任何一方之前以 `PROVIDER_CHANGED` 拒绝;调用方可根据当前注册重试委派。以下创建失败均为 `SubagentError`:超出请求深度的子代以 `SubagentDepthError` 子类和 `DEPTH_EXCEEDED` 拒绝,无效的运行时 `subagentDepth` 以 `INVALID_DEPTH` 拒绝,所选 preset 未知或无法加载、或无法加入创建者 preset 版本的新建子代以 `PRESET_UNAVAILABLE` 拒绝,缺少工作目录服务的本地子代以 `WORKING_DIRECTORY_UNAVAILABLE` 拒绝,cwd 为相对路径或不可进入的进程外子代以 `INVALID_CWD` 拒绝。持久化 descriptor 损坏的冷目标以 `NOT_RESUMABLE` 拒绝,有待处理输入时调用 `structured_output` 以 `STRUCTURED_OUTPUT_PENDING_INPUT` 失败。调用方信号仅取消尚未发布的工作;发布后通过 `dispose()` 取消该次 activation,并等待其资源清理完成。创建后代独立继续运行;宿主必须在释放根句柄前等待 `drainDescendants([root])`,以停止所有成员并等待正在启动的工作。`result` 在清理与通知结束后完成,携带输出、可选结构化数据与停止原因;结果捕获故障在清理后使其拒绝。清理失败使 `dispose()` 拒绝,并将生命周期结束事件标记为失败;结果 promise 与父级通知保留已捕获的执行结果。 +缺少 `agents` 服务时,启动请求以 `CONTINUATION_UNAVAILABLE` 拒绝;运行时可用但父级缺失或被替换时,以 `UNAUTHORIZED` 拒绝。未实现任何执行方法的提供方会在注册时以 `UNSUPPORTED_CAPABILITY` 被拒绝;请求不受支持的能力会以同一码使创建失败。如果等待目录解析期间提供方被移除或替换,创建会在调用任何一方之前以 `PROVIDER_CHANGED` 拒绝;调用方可根据当前注册重试委派。以下创建失败均为 `SubagentError`:超出请求深度的子代以 `SubagentDepthError` 子类和 `DEPTH_EXCEEDED` 拒绝,无效的运行时 `subagentDepth` 以 `INVALID_DEPTH` 拒绝,无法加入创建者 preset 版本的子代以 `PRESET_UNAVAILABLE` 拒绝(所选 preset 未知或无法加载时保留 registry 的 `RemoteError` code),缺少工作目录服务的本地子代以 `WORKING_DIRECTORY_UNAVAILABLE` 拒绝,cwd 为相对路径或不可进入的进程外子代以 `INVALID_CWD` 拒绝。持久化 descriptor 损坏的冷目标以 `NOT_RESUMABLE` 拒绝,有待处理输入时调用 `structured_output` 以 `STRUCTURED_OUTPUT_PENDING_INPUT` 失败。调用方信号仅取消尚未发布的工作;发布后通过 `dispose()` 取消该次 activation,并等待其资源清理完成。创建后代独立继续运行;宿主必须在释放根句柄前等待 `drainDescendants([root])`,以停止所有成员并等待正在启动的工作。`result` 在清理与通知结束后完成,携带输出、可选结构化数据与停止原因;结果捕获故障在清理后使其拒绝。清理失败使 `dispose()` 拒绝,并将生命周期结束事件标记为失败;结果 promise 与父级通知保留已捕获的执行结果。 ----- diff --git a/packages/subagent/subagent/package.json b/packages/subagent/subagent/package.json index 6bff46b9ee..7bfdb4194b 100644 --- a/packages/subagent/subagent/package.json +++ b/packages/subagent/subagent/package.json @@ -109,6 +109,7 @@ "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-agent-preset-registry": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-sandbox": "workspace:*", "@deepseek-ai/dsh-sandbox-policy": "workspace:*", diff --git a/packages/subagent/subagent/src/child-agent.ts b/packages/subagent/subagent/src/child-agent.ts index 89b2a59447..bbc669b363 100644 --- a/packages/subagent/subagent/src/child-agent.ts +++ b/packages/subagent/subagent/src/child-agent.ts @@ -25,7 +25,6 @@ import type {} from '@deepseek-ai/dsh-permission-presets' // keeps its model-facing rows on the host plane, where the child already sees // them through the tool registry's global layer. import type {} from '@deepseek-ai/dsh-agent-preset-registry' -import { remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' import { delegationDepthOf } from './depth.ts' import { SubagentError } from './error.ts' @@ -184,9 +183,9 @@ export const SUBAGENT_DELEGATION_CONTEXT * @param parent - creator for fresh delegation; absent during target-only restoration. * @param composition - independent preset and any overrides read from a historical descriptor. * @returns A promise when mounting an independent preset; otherwise completes synchronously. - * @throws {SubagentError} `PRESET_UNAVAILABLE` when the preset service is absent, a fresh - * delegation's preset is unknown or cannot load, or the child cannot join its creator's - * preset revision. Restoration propagates the registry's `RemoteError` unchanged. + * @throws {SubagentError} `PRESET_UNAVAILABLE` when the preset service is absent or the + * child cannot join its creator's preset revision. An unknown or unloadable selected + * preset rejects with the registry's `RemoteError` code. */ export function applyChildComposition( childCtx: Context, @@ -198,12 +197,7 @@ export function applyChildComposition( if (presets === undefined) { throw new SubagentError('selecting a child agent preset requires the agent-presets service', 'PRESET_UNAVAILABLE') } - const mounted = presets.mount(childCtx, composition.agentPreset) - // Restoration leaves an unavailable preset to its caller's NOT_RESUMABLE classification. - return (parent === undefined ? mounted : mounted.catch((error: unknown) => { - const failure = remoteErrorOf(error) - throw failure === undefined ? error : new SubagentError(failure.message, 'PRESET_UNAVAILABLE', { cause: error }) - })).then(() => { + return presets.mount(childCtx, composition.agentPreset).then(() => { applyChildOverrides(childCtx, composition) }) } diff --git a/packages/subagent/subagent/tests/continuation-presets.spec.ts b/packages/subagent/subagent/tests/continuation-presets.spec.ts index 0cd3e0f69b..1dad8a15b1 100644 --- a/packages/subagent/subagent/tests/continuation-presets.spec.ts +++ b/packages/subagent/subagent/tests/continuation-presets.spec.ts @@ -13,6 +13,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import AgentPresets from '@deepseek-ai/dsh-agent-preset-registry' +import { HarnessError } from '@deepseek-ai/dsh-error' import { createUserMessage } from '@deepseek-ai/dsh-llm' import { SessionId } from '@deepseek-ai/dsh-session' import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' @@ -139,17 +140,11 @@ describe('child preset start validation', () => { expect(adapter.requests).toEqual([]) }) - it('classifies an unknown independent preset as PRESET_UNAVAILABLE and keeps other mount failures', async () => { + it('rejects an unknown independent preset with the registry RemoteError as a HarnessError', async () => { const { ctx, parent, adapter } = await setup() - await expect(ctx.subagents.startActivation(startSpec(parent, 'absent'))).rejects.toMatchObject({ - name: 'SubagentError', - code: 'PRESET_UNAVAILABLE', - message: 'Unknown agent preset: absent', - cause: { code: 'agent-preset/not-found' }, - }) - const failure = new Error('binding failed') - vi.spyOn(ctx.agentPresets, 'mount').mockRejectedValueOnce(failure) - await expect(ctx.subagents.startActivation(startSpec(parent, 'reviewing'))).rejects.toBe(failure) + const failure: unknown = await ctx.subagents.startActivation(startSpec(parent, 'absent')).catch((error: unknown) => error) + expect(failure).toBeInstanceOf(HarnessError) + expect(failure).toMatchObject({ name: 'RemoteError', code: 'agent-preset/not-found', message: 'Unknown agent preset: absent' }) expect(ctx.agents.list().map(agent => agent.id)).toEqual([parent.id]) expect(adapter.requests).toEqual([]) }) diff --git a/packages/subagent/tool-subagent/tests/preset-selection.spec.ts b/packages/subagent/tool-subagent/tests/preset-selection.spec.ts index 920697c323..a29e780d36 100644 --- a/packages/subagent/tool-subagent/tests/preset-selection.spec.ts +++ b/packages/subagent/tool-subagent/tests/preset-selection.spec.ts @@ -162,7 +162,7 @@ describe('spawn preset selection', () => { const result = await callSubagent(ctx, { ...args, ...selection }, { agent: parent.agent }) expect(result.isError).toBe(true) expect(text(result)).toContain('Unknown agent preset: absent') - expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'PRESET_UNAVAILABLE' }) + expect(result.error?.info).toEqual({ name: 'RemoteError', code: 'agent-preset/not-found' }) expect(ctx.agents.list()).toEqual([parent.agent]) expect(ctx.sessions.list()).toEqual(sessions) }) @@ -180,7 +180,7 @@ describe('spawn preset selection', () => { const result = await callSubagent(ctx, args, { agent: parent.agent }) expect(result.isError).toBe(true) expect(text(result)).toContain('missing-plugin') - expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'PRESET_UNAVAILABLE' }) + expect(result.error?.info).toEqual({ name: 'RemoteError', code: 'agent-preset/invalid' }) expect(ctx.agents.list()).toEqual([parent.agent]) expect(ctx.sessions.list()).toEqual(sessions) }) @@ -365,7 +365,7 @@ describe('spawn preset selection', () => { const failed = await callSubagent(ctx, args, { agent: handle.agent }) expect(failed.isError).toBe(true) expect(text(failed)).toContain('Unknown agent preset: later') - expect(failed.error?.info).toEqual({ name: 'SubagentError', code: 'PRESET_UNAVAILABLE' }) + expect(failed.error?.info).toEqual({ name: 'RemoteError', code: 'agent-preset/not-found' }) await ctx.agentPresets.register({ id: 'later', plugins: [] }) ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('reviewed')])) diff --git a/packages/typert/protocol/README.i18n.yaml b/packages/typert/protocol/README.i18n.yaml index 018aebf137..aebf5c816e 100644 --- a/packages/typert/protocol/README.i18n.yaml +++ b/packages/typert/protocol/README.i18n.yaml @@ -27,8 +27,8 @@ en: 3db384ae6f215632 zh: 56207184b09d4018 /deepseek-ai-dsh-typert-protocol/use-this-package/reporting-and-reading-a-remote-failure: - en: 4ba5266ddb014029 - zh: e31ae6438b9b4aa5 + en: 32d5fdd4b678d86c + zh: 00af91a97b891592 /deepseek-ai-dsh-typert-protocol/use-this-package/receiving-forwarded-host-events-on-the-client: en: 1101bd1d1419618c zh: 6ff036538d237e0a diff --git a/packages/typert/protocol/README.md b/packages/typert/protocol/README.md index 8613555bf7..c85039ab3e 100644 --- a/packages/typert/protocol/README.md +++ b/packages/typert/protocol/README.md @@ -81,7 +81,7 @@ declare module '@deepseek-ai/dsh-typert-protocol' { throw new RemoteError('goal/not-found', `goal "${id}" does not exist`, { goalId: id }) ``` -An owner throws at the failure point; no package writes an error-class family or an exit-mapping function. A caller discriminates by `code` — never by `instanceof` — and a `code` branch narrows `details` with no cast, because `RemoteFailure` is the code-discriminated union of `RemoteError` instances. Infrastructure that must recognize a failure carried across a module or realm copy of the class calls `remoteErrorOf(value)`, which reads a structural marker instead of the prototype chain. +An owner throws at the failure point; no package writes an error-class family or an exit-mapping function. A caller discriminates by `code` — never by `instanceof` — and a `code` branch narrows `details` with no cast, because `RemoteFailure` is the code-discriminated union of `RemoteError` instances. Infrastructure that must recognize a failure carried across a module or realm copy of the class calls `remoteErrorOf(value)`, which reads a structural marker instead of the prototype chain. `RemoteError` extends `HarnessError` from [`@deepseek-ai/dsh-error`](../../util/error/README.md), so a tool body that throws one records `name: 'RemoteError'` and its Remote `code` on `tool/result`. ### Receiving forwarded Host events on the Client diff --git a/packages/typert/protocol/README.zh.md b/packages/typert/protocol/README.zh.md index f02a8f5217..849a9c07be 100644 --- a/packages/typert/protocol/README.zh.md +++ b/packages/typert/protocol/README.zh.md @@ -81,7 +81,7 @@ declare module '@deepseek-ai/dsh-typert-protocol' { throw new RemoteError('goal/not-found', `goal "${id}" does not exist`, { goalId: id }) ``` -拥有方在失败点直接抛出;没有任何包再写错误类家族或出口映射函数。调用方按 `code` 判别——绝不用 `instanceof`——且 `code` 分支无需 cast 即收窄 `details`,因为 `RemoteFailure` 就是 `RemoteError` 实例按码判别的 union。需要识别跨模块或跨 realm 类副本传来的失败时,基础设施调用 `remoteErrorOf(value)`,它读结构标记而不是原型链。 +拥有方在失败点直接抛出;没有任何包再写错误类家族或出口映射函数。调用方按 `code` 判别——绝不用 `instanceof`——且 `code` 分支无需 cast 即收窄 `details`,因为 `RemoteFailure` 就是 `RemoteError` 实例按码判别的 union。需要识别跨模块或跨 realm 类副本传来的失败时,基础设施调用 `remoteErrorOf(value)`,它读结构标记而不是原型链。`RemoteError` 继承 [`@deepseek-ai/dsh-error`](../../util/error/README.zh.md) 的 `HarnessError`,因此工具体抛出它时,`tool/result` 会记录 `name: 'RemoteError'` 及其 Remote `code`。 ### 在 Client 侧接收转发的 Host 事件 diff --git a/packages/typert/protocol/package.json b/packages/typert/protocol/package.json index 7fcc8f87f0..efb5f07aed 100644 --- a/packages/typert/protocol/package.json +++ b/packages/typert/protocol/package.json @@ -43,9 +43,11 @@ "zod": "4.6.6" }, "peerDependencies": { - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-error": "workspace:*" }, "devDependencies": { - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/typert/protocol/src/remote-error.ts b/packages/typert/protocol/src/remote-error.ts index 90430a2093..476787eab9 100644 --- a/packages/typert/protocol/src/remote-error.ts +++ b/packages/typert/protocol/src/remote-error.ts @@ -1,15 +1,17 @@ /** The one Remote failure class shared by owners, the Gateway, and consumers. */ +import { HarnessError } from '@deepseek-ai/dsh-error' import type { RemoteErrorCode, RemoteErrorDetailsMap, RemoteFailure } from './types.ts' /** - * One Remote call failure: a real Error carrying its stable code and typed + * One Remote call failure: a `HarnessError` carrying its stable code and typed * details. Owners throw it at the failure point; the Host Gateway encodes it * onto the wire unchanged; the Client face rebuilds an instance for the * `RemoteResult` error branch, so `throw result.error` keeps throw semantics. - * Discrimination is always by `code`, never by instanceof. + * A tool body that throws it records `name: 'RemoteError'` and its Remote code + * on `tool/result`. Discrimination is always by `code`, never by instanceof. */ -export class RemoteError extends Error { +export class RemoteError extends HarnessError { /** Structural marker: cross-realm/bundle identification never uses instanceof. */ readonly isDSHRemoteError: true = true @@ -20,12 +22,12 @@ export class RemoteError extends * @param options - standard Error options (`cause` survives in-process only). */ constructor( - readonly code: Code, + override readonly code: Code, message: string, readonly details: RemoteErrorDetailsMap[Code], options?: ErrorOptions, ) { - super(message, options) + super(message, code, options) this.name = 'RemoteError' } } diff --git a/packages/typert/protocol/tests/remote-error.spec.ts b/packages/typert/protocol/tests/remote-error.spec.ts new file mode 100644 index 0000000000..54c8388018 --- /dev/null +++ b/packages/typert/protocol/tests/remote-error.spec.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest' +import { HarnessError } from '@deepseek-ai/dsh-error' +import { RemoteError, remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' + +describe('RemoteError', () => { + it('is a HarnessError that keeps its Remote code, details, and cause', () => { + const cause = new Error('backend closed') + const error = new RemoteError('gateway/bad-request', 'name is required', { issues: [{ path: ['name'] }] }, { cause }) + + expect(error).toBeInstanceOf(HarnessError) + expect(error).toMatchObject({ + name: 'RemoteError', + code: 'gateway/bad-request', + message: 'name is required', + details: { issues: [{ path: ['name'] }] }, + cause, + }) + expect(remoteErrorOf(error)).toBe(error) + }) +}) diff --git a/packages/typert/protocol/tsconfig.json b/packages/typert/protocol/tsconfig.json index 342f636170..4f9fae2080 100644 --- a/packages/typert/protocol/tsconfig.json +++ b/packages/typert/protocol/tsconfig.json @@ -16,6 +16,9 @@ }, { "path": "../../util/brand" + }, + { + "path": "../../util/error" } ] } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9d71501a7c..29ea75b0e4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -16442,6 +16442,9 @@ importers: '@deepseek-ai/dsh-attachment': specifier: workspace:* version: link:../../attachment/attachment + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-fs-sandbox': specifier: workspace:* version: link:../../fs/fs-sandbox @@ -17708,6 +17711,9 @@ importers: '@deepseek-ai/cordis': specifier: workspace:~ version: link:../../../vendor/cordis + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error packages/typert/registry: dependencies: From ba1a12b72edf32318811df3f11831b97d342d79a Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 6 Nov 2026 18:02:48 +0800 Subject: [PATCH 047/404] fix(panel): keep the working folder separator out of the accessible text --- .../client/ui-session-panel/src/client/ProjectRow.module.css | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/client/ui-session-panel/src/client/ProjectRow.module.css b/packages/client/ui-session-panel/src/client/ProjectRow.module.css index d0d430e14d..0e99b68fd7 100644 --- a/packages/client/ui-session-panel/src/client/ProjectRow.module.css +++ b/packages/client/ui-session-panel/src/client/ProjectRow.module.css @@ -1,7 +1,8 @@ /* [name] · [parent]: the name keeps its width up to the row, and the parent fills the rest of the line and clips with an ellipsis. With less than 5em left for it, the parent wraps onto a second line, which the one-line height - hides, so the row never shows a separator without a parent. */ + hides, so the row never shows a separator without a parent. The separator + is decorative, so assistive technology reads the name and the parent alone. */ .folder { display: flex; @@ -36,5 +37,5 @@ .parent::before { padding: 0 4px; - content: '·'; + content: '·' / ''; } From 3aee25862d5d9b1681a15998cb9086c448a7224f Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 6 Nov 2026 18:15:52 +0800 Subject: [PATCH 048/404] ci(preview): link the snapshot diff page from the source chooser and harden it Co-authored-by: yudshj <16971372+yudshj@users.noreply.github.com> --- .github/preview-sizing/README.i18n.yaml | 4 +- .github/preview-sizing/README.md | 2 +- .github/preview-sizing/README.zh.md | 2 +- .../workflows/build-preview-cloudflare.yml | 36 ++- apps/web/tests/preview-boot.e2e.ts | 1 + .../experimental/webworker-packer/src/bin.ts | 1 + .../webworker-runtime/README.i18n.yaml | 4 +- .../experimental/webworker-runtime/README.md | 2 +- .../webworker-runtime/README.zh.md | 2 +- .../webworker-runtime/src/client/index.ts | 2 +- .../src/client/source-chooser.ts | 21 +- .../webworker-runtime/src/fixture-manifest.ts | 31 ++- .../webworker-runtime/src/index.ts | 2 +- .../tests/client/source-chooser.spec.ts | 26 ++ .../tests/fixture-manifest.spec.ts | 13 + scripts/preview-workflow.spec.ts | 15 +- scripts/snapshot-diff-page.spec.ts | 90 ++++--- scripts/snapshot-diff-page.ts | 229 ++++++++++++------ 18 files changed, 345 insertions(+), 138 deletions(-) diff --git a/.github/preview-sizing/README.i18n.yaml b/.github/preview-sizing/README.i18n.yaml index 065a63ad3e..2bb1cc7311 100644 --- a/.github/preview-sizing/README.i18n.yaml +++ b/.github/preview-sizing/README.i18n.yaml @@ -15,8 +15,8 @@ en: 2374f332d040ece2 zh: 7f914fb83cfb5caa /pr-preview-runner-sizing/publication-semantics: - en: 25ee2f4b26ef7770 - zh: 788b7fb4bee6e159 + en: 0d86702bcbbe23f4 + zh: cd0041c917ac8c55 /pr-preview-runner-sizing/dev-note: en: c3e8959997c4d5d0 zh: 109a391915c2bdfb diff --git a/.github/preview-sizing/README.md b/.github/preview-sizing/README.md index 5fcec8ad2c..fe47f0119e 100644 --- a/.github/preview-sizing/README.md +++ b/.github/preview-sizing/README.md @@ -26,7 +26,7 @@ A build-only benchmark does not deploy, access Cloudflare credentials, or post p ## Publication semantics -Runner selection does not alter pull-request events, per-PR cancellation, immutable installation, restore-only dependency caching, full workspace build, preview packing, sourcemap removal, or the preview page copied to the deployment root. Cloudflare uploads only the built site to the PR branch alias. The protected-image check requires HTTP 200, no transport content encoding, and gzip magic bytes; the URL comment remains idempotent. Dependabot and other PR authors remain on GitHub-hosted machines. +Runner selection does not alter pull-request events, per-PR cancellation, immutable installation, restore-only dependency caching, full workspace build, preview packing, sourcemap removal, or the preview page copied to the deployment root. Cloudflare uploads only the built site and the snapshot diff page to the PR branch alias; that page embeds committed `snapshots/` diff text, never package sources. The protected-image check requires HTTP 200, no transport content encoding, and gzip magic bytes; the URL comment remains idempotent. Dependabot and other PR authors remain on GitHub-hosted machines. diff --git a/.github/preview-sizing/README.zh.md b/.github/preview-sizing/README.zh.md index 43258d716a..36770bb7c5 100644 --- a/.github/preview-sizing/README.zh.md +++ b/.github/preview-sizing/README.zh.md @@ -26,7 +26,7 @@ ## 发布语义 -运行器选择不改变 PR 事件、按 PR 取消、不可变安装、只恢复的依赖缓存、完整工作区构建、预览打包、sourcemap 删除,以及复制到部署根目录的预览页面。Cloudflare 仅将构建站点上传至 PR 分支别名。受保护镜像检查要求 HTTP 200、无传输内容编码及 gzip 魔数字节;URL 评论保持幂等。Dependabot 与其他 PR 作者仍使用 GitHub 托管机器。 +运行器选择不改变 PR 事件、按 PR 取消、不可变安装、只恢复的依赖缓存、完整工作区构建、预览打包、sourcemap 删除,以及复制到部署根目录的预览页面。Cloudflare 仅将构建站点和 snapshot diff 页面上传至 PR 分支别名;该页面嵌入已提交的 `snapshots/` diff 文本,不含包源码。受保护镜像检查要求 HTTP 200、无传输内容编码及 gzip 魔数字节;URL 评论保持幂等。Dependabot 与其他 PR 作者仍使用 GitHub 托管机器。 diff --git a/.github/workflows/build-preview-cloudflare.yml b/.github/workflows/build-preview-cloudflare.yml index c8cb718234..c9f60f3282 100644 --- a/.github/workflows/build-preview-cloudflare.yml +++ b/.github/workflows/build-preview-cloudflare.yml @@ -2,7 +2,8 @@ name: Build PR preview # Every push to a pull request publishes that pull request's preview to # Cloudflare Pages under its own branch alias, behind Cloudflare Access. The -# upload carries build products only: the workflow never grants the deployment +# upload carries build products plus the snapshot diff page, which embeds +# committed `snapshots/` diff text: the workflow never grants the deployment # platform access to this repository's sources. This lane also owns the # aggregate test and script type checks that the required Linux consumers no # longer repeat on every pull request. @@ -102,9 +103,16 @@ jobs: cp apps/web/dist/preview.html apps/web/dist/index.html # Reviewers read snapshot changes at /snapshot-diff/, which opens on the - # SDK blank-Session catalog (system prompt and tool schemas). + # SDK blank-Session catalog (system prompt and tool schemas); the source + # chooser links to it. The page serves review only, so a failure warns + # like publication instead of failing the build. - name: Render the snapshot diff page - run: pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD --out apps/web/dist/snapshot-diff/index.html + id: snapshot-diff + continue-on-error: true + run: >- + pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD + --out apps/web/dist/snapshot-diff/index.html + --preview-manifest apps/web/dist/preview/fixtures.json - name: Upload to Cloudflare Pages id: upload @@ -180,29 +188,33 @@ jobs: env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} PR: ${{ github.event.pull_request.number }} + SNAPSHOT_DIFF: ${{ steps.snapshot-diff.outcome }} run: | marker='' url="https://pr-$PR.${CF_PROJECT}.pages.dev" + links="[Preview for #$PR]($url)" + if [ "$SNAPSHOT_DIFF" = success ]; then links="$links · [snapshot changes]($url/snapshot-diff/)"; fi # The marker sits on its own line: markdown renders no link on a # line that opens with a raw HTML comment. - body=$(printf '%s\n\n%s\n' \ - "$marker" \ - "[Preview for #$PR]($url) · [snapshot changes]($url/snapshot-diff/) (requires Cloudflare Access sign-in)") + body=$(printf '%s\n\n%s\n' "$marker" "$links (requires Cloudflare Access sign-in)") existing=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR/comments" --paginate \ - --jq "[.[] | select(.body | contains(\"$marker\"))] | first // empty | [.id, .body] | @json") + --jq "[.[] | select(.user.login == \"github-actions[bot]\" and (.body | contains(\"$marker\")))] | first // empty | [.id, .body] | @json") if [ -z "$existing" ]; then - printf '%s\n' "$body" | gh pr comment "$PR" --body-file - + printf '%s' "$body" | gh pr comment "$PR" --body-file - elif [ "$(jq -r '.[1]' <<< "$existing")" != "$body" ]; then gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$(jq -r '.[0]' <<< "$existing")" -f body="$body" > /dev/null else echo "preview URL already commented" fi - # Publishing stays outside the required verdict: a Cloudflare, Access, or - # comment failure warns, while a build failure still fails this check. + # Publishing stays outside the required verdict: a snapshot diff page, + # Cloudflare, Access, or comment failure warns, while a build failure + # still fails this check. - name: Report preview publication failures - if: steps.upload.outcome == 'failure' || steps.verify.outcome == 'failure' || steps.comment.outcome == 'failure' + if: >- + steps.snapshot-diff.outcome == 'failure' || steps.upload.outcome == 'failure' + || steps.verify.outcome == 'failure' || steps.comment.outcome == 'failure' run: | - message='preview publication failed; the build passed, see the upload, verify, and comment steps' + message='preview publication failed; the build passed, see the snapshot diff, upload, verify, and comment steps' echo "::warning::$message" echo "$message" >> "$GITHUB_STEP_SUMMARY" diff --git a/apps/web/tests/preview-boot.e2e.ts b/apps/web/tests/preview-boot.e2e.ts index f1ea40b25c..70542e08d3 100644 --- a/apps/web/tests/preview-boot.e2e.ts +++ b/apps/web/tests/preview-boot.e2e.ts @@ -200,6 +200,7 @@ function requireVfsAssets(): PreviewAssets { version: PREVIEW_FIXTURE_MANIFEST_VERSION, defaultFixture: fixtures[0]?.id ?? null, fixtures, + links: [], } writeAsset(`preview/${PREVIEW_FIXTURE_MANIFEST_FILE}`, `${JSON.stringify(fixtureManifest, null, 2)}\n`) return { overrides, manifest, cleanup: () => { rmSync(directory, { recursive: true, force: true }) } } diff --git a/packages/experimental/webworker-packer/src/bin.ts b/packages/experimental/webworker-packer/src/bin.ts index 18bf398e59..202b382724 100644 --- a/packages/experimental/webworker-packer/src/bin.ts +++ b/packages/experimental/webworker-packer/src/bin.ts @@ -80,6 +80,7 @@ const manifest: PreviewFixtureManifest = { version: PREVIEW_FIXTURE_MANIFEST_VERSION, defaultFixture: fixtures[0]?.id ?? null, fixtures, + links: [], } writeFileSync( join(dirname(outputFile), PREVIEW_FIXTURE_MANIFEST_FILE), diff --git a/packages/experimental/webworker-runtime/README.i18n.yaml b/packages/experimental/webworker-runtime/README.i18n.yaml index 68deb797c2..c4578dcd12 100644 --- a/packages/experimental/webworker-runtime/README.i18n.yaml +++ b/packages/experimental/webworker-runtime/README.i18n.yaml @@ -15,8 +15,8 @@ en: 4e53164159b5ce41 zh: 89582dc0294d0776 /deepseek-ai-dsh-experimental-webworker-runtime/use-this-package: - en: 9f4c76d6c4391037 - zh: c55611045f4667e2 + en: 33c27e81e1e6212c + zh: 6e32be50142bdb44 /deepseek-ai-dsh-experimental-webworker-runtime/model-experience: en: 61fce9b4c7dc96e6 zh: dc2d931063a38327 diff --git a/packages/experimental/webworker-runtime/README.md b/packages/experimental/webworker-runtime/README.md index e2bd1605ef..eeae07447e 100644 --- a/packages/experimental/webworker-runtime/README.md +++ b/packages/experimental/webworker-runtime/README.md @@ -31,7 +31,7 @@ Three build artifacts and one source-owned process layer: - **Lazy archives** — the manifest registers each page chunk the packer moved out of the base image by path and size, with its archive name relative to the image URL. Existence, stats, and listings answer at once; the first asynchronous read (`fs.promises.readFile`, `fs.promises.open`, `fs.createReadStream`, `fs.promises.cp`) fetches and inflates that archive once for every waiting reader, checks it against the registration, and mounts its files without publishing a mutation. A failed fetch rejects the read and leaves the files registered, so the next read fetches again. Until then, synchronous reads, writes, appends, truncation, chmod, rename, and link of a registered file fail with `ERR_DSH_VFS_DEFERRED` naming the archive; unlink and recursive removal drop the registration, and seeding the path replaces it. The archive name derives from its content digest, and the fetch checks only the registered paths and sizes, not the digest. An image that registers lazy archives must be passed as a URL. - **`lib/worker.js` (worker bundle)** — the assembly plus this package's Node-compatibility layer as one self-contained ES module. The module proxy table (`module-proxies.ts`) is the only platform fork: `node:*` builtins over VFS/tunnel/browser primitives, structural stubs that fail loud on the console for what a browser cannot do, and native/binary package replacements. `node:module` supplies `createRequire().resolve` and `.resolve.paths()` over the image package root, so unchanged packages can discover manifests without evaluating their modules. `node-addon-require-builtin` answers the Node v24.18.0 internal modules that the vendored Loader, app-boot, and HMR read without `--expose-internals`: the cascaded ESM loader's `resolveSync` and `import` over the Worker loader, with Node's `ERR_MODULE_NOT_FOUND` and `ERR_PACKAGE_PATH_NOT_EXPORTED` codes, and an empty `loadCache`; and the CommonJS loader, package reader, `modules` binding, and resolve-cache members that HMR replaces, which refuse when called. `process.versions.node` reports `24.18.0`, so `ModuleLoader.fromInternal()` and the Loader's `internal` reach that cascaded loader. `node:path.win32.isAbsolute` and `node:util.inherits` follow Node; other `win32` members throw. The `node:util` JSON-data comparator compares own enumerable properties, preserving Node admission decisions for recorded fields such as `__proto__`. The global `process` shim carries Node detection fields including `title`, preventing Worker execution from entering DOM-only branches; Node’s `global` alias references the same `globalThis` object for image-loaded packages. The pack-time parser reports statically named module requests, including module-scope direct calls of the form `createRequire(import.meta.url)('pkg')` through a named `node:module` or `module` import, to the packer's reachability walk. Stored, CommonJS-obtained, and rebased `createRequire` calls require image entry seeds. Lowered bodies read named and default imports through the required module object at each reference, so a module in an import cycle observes a binding once the exporting module initializes it; in a module with such imports, an assignment to an imported binding, a direct `eval`, and a declaration using the reserved `__dsh$` prefix fail the pack. VFS mutations drive `node:fs` callback, polling, and promise watchers, whose listeners run in the async context where the watcher was created rather than that of the writing code; open descriptors retain file identity and access mode across rename, replacement, and unlink, `FileHandle.stat({ bigint: true })` reports the same device and inode identity as a path stat while the name still refers to that file, and `FileHandle.chmod()` updates the opened file identity; `readable-stream` supplies `node:stream/promises` completion and pipeline helpers and the stream state machine used by file streams and unchanged image packages such as Chokidar and readdirp. The maintained `string_decoder` package supplies `node:string_decoder`, retaining incomplete multibyte characters between chunks. AsyncLocalStorage carries sync-stack causality across `await` through the snapshot/restore faces the pack-time lowering injects. The worker holds no compiler: an image the packer did not lower is refused at mount. The callback `fs.realpath.native` alias resolves within the mounted VFS and supports `util.promisify`. - **`src/shell/` (the worker's own process layer)** — a browser worker cannot fork, so `node:child_process` is not a stub but an implementation: `spawn` starts the command in its own Web Worker — this same bundle, told by its first frame to be a shell process — and reports it through the `ChildProcess` surface the subprocess service consumes. The command runs off the host's thread, `SIGKILL` terminates it whatever it is doing, and it reaches the VFS only by message (the host serves those frames). Worker platform executables preserve native-package protocols such as Landlock without replacing their JavaScript packages or coupling their implementations to `node:child_process`; `xdg-open` sends one VFS text file to the page's read-only viewer, so desktop-opener actions such as **Open configuration file** show the file in the page; ordinary commands use the package's evaluator and coreutils command table. The grammar is `@yarnpkg/parsers`' `parseShell`, while `execSync`/`fork` still refuse because they need a real process. -- **`lib/client.js` (page half)** — startup has two independent stages. `chooseWorkerHostSource({ image?, fixtureManifest? })` optionally owns the boot barrier and fixture manifest: without `preview-fixture` it waits at the source chooser, while a valid query selects directly; either path returns ordered overlays. `connectWorkerHost(worker, { image?, overlays? })` remains the public base-runtime connector; callers that skip the chooser get an empty overlay list. `apps/web` invokes both and supplies its statically bundled Worker. The opening `init` frame carries the base and ordered overlay URLs, the boot payload delivers the structured index-injection table, and `applyIndexInjections` executes it before the shell entry runs. Script preload rows are advisory and skipped because `/plugins` resources resolve only through the tunnel; `loadBundle` fetches each combo on first demand, embeds its tunnel-only source map as a Base64 data URL, and executes the script as a Blob. Before the shell entry runs, the page reads `GET /__assets__`, which the tunnel answers with an uncompressed tar of every package asset in the image, and supplies `resolveAsset`, which maps each `plugins//assets/` reference a bundle passes to `require.asset` to a Blob URL of those bytes. The worker's unsolicited `view-text` frame opens the page's modal text viewer. The tunnel also exposes fetch-shaped transport, the independent file-upload carrier, and the API client. Request frames preserve Blob bodies through structured clone and transfer `ReadableStream` ownership. The Host Worker streams both forms into the route, so neither browser thread creates a complete byte array for a generic-file upload. A Remote stream's uplink crosses as `stream-uplink-item` / `stream-uplink-end` frames into an unbounded `TunnelUplink` that drops items arriving after `end`: the page and its worker are one trusted same-origin boundary, so the Host inbox cap does not apply. +- **`lib/client.js` (page half)** — startup has two independent stages. `chooseWorkerHostSource({ image?, fixtureManifest? })` optionally owns the boot barrier and fixture manifest: without `preview-fixture` it waits at the source chooser, while a valid query selects directly; either path returns ordered overlays. The manifest's optional `links` list of relative URLs renders beside the start button; the PR preview workflow adds one for its snapshot diff page. `connectWorkerHost(worker, { image?, overlays? })` remains the public base-runtime connector; callers that skip the chooser get an empty overlay list. `apps/web` invokes both and supplies its statically bundled Worker. The opening `init` frame carries the base and ordered overlay URLs, the boot payload delivers the structured index-injection table, and `applyIndexInjections` executes it before the shell entry runs. Script preload rows are advisory and skipped because `/plugins` resources resolve only through the tunnel; `loadBundle` fetches each combo on first demand, embeds its tunnel-only source map as a Base64 data URL, and executes the script as a Blob. Before the shell entry runs, the page reads `GET /__assets__`, which the tunnel answers with an uncompressed tar of every package asset in the image, and supplies `resolveAsset`, which maps each `plugins//assets/` reference a bundle passes to `require.asset` to a Blob URL of those bytes. The worker's unsolicited `view-text` frame opens the page's modal text viewer. The tunnel also exposes fetch-shaped transport, the independent file-upload carrier, and the API client. Request frames preserve Blob bodies through structured clone and transfer `ReadableStream` ownership. The Host Worker streams both forms into the route, so neither browser thread creates a complete byte array for a generic-file upload. A Remote stream's uplink crosses as `stream-uplink-item` / `stream-uplink-end` frames into an unbounded `TunnelUplink` that drops items arriving after `end`: the page and its worker are one trusted same-origin boundary, so the Host inbox cap does not apply. Callbacks and timers registered under an explicit root context retain its empty stores, so they cannot inherit an unrelated transaction. diff --git a/packages/experimental/webworker-runtime/README.zh.md b/packages/experimental/webworker-runtime/README.zh.md index b666c692d8..b09bc78a5b 100644 --- a/packages/experimental/webworker-runtime/README.zh.md +++ b/packages/experimental/webworker-runtime/README.zh.md @@ -31,7 +31,7 @@ kind: "package-library" - **懒加载归档**——manifest 按路径和大小登记 packer 移出基础镜像的每个页面 chunk,并给出相对镜像 URL 的归档名。存在性、stat 和目录列表立即作答;第一次异步读取(`fs.promises.readFile`、`fs.promises.open`、`fs.createReadStream`、`fs.promises.cp`)为所有等待中的读取方只拉取并解压一次该归档,按登记内容校验后挂载其文件,不发布 mutation。拉取失败时本次读取被拒绝,文件保持登记状态,下次读取会重新拉取。在此之前,对已登记文件的同步读取、写入、追加、截断、chmod、rename 和 link 会以 `ERR_DSH_VFS_DEFERRED` 失败,错误中写明归档名;unlink 和递归删除会移除登记,再次 seed 该路径会替换登记。归档名由内容摘要派生,拉取时只校验登记的路径和大小,不校验摘要。登记了懒加载归档的镜像必须以 URL 传入。 - **`lib/worker.js`(worker 束)**——装配库加本包的 Node 兼容层,合成一个自含 ES module。模块代理表(`module-proxies.ts`)是唯一平台叉口:`node:*` 内建走 VFS、隧道和浏览器原语,浏览器做不到的走结构化 stub(调用即在 console 报错并抛出),native/binary 包则替换执行后端。`node:module` 在镜像 package 根之上提供 `createRequire().resolve` 与 `.resolve.paths()`,使未修改的包无需执行目标模块即可发现 manifest。`node-addon-require-builtin` 应答 vendor Loader、app-boot 和 HMR 在没有 `--expose-internals` 时读取的 Node v24.18.0 internal 模块:cascaded ESM loader 的 `resolveSync` 和 `import` 经 Worker 加载器完成,失败时带 Node 的 `ERR_MODULE_NOT_FOUND` 与 `ERR_PACKAGE_PATH_NOT_EXPORTED` 错误码,`loadCache` 为空;HMR 会替换的 CommonJS loader、package reader、`modules` binding 与 resolve cache 成员被调用时拒绝。`process.versions.node` 报告 `24.18.0`,因此 `ModuleLoader.fromInternal()` 和 Loader 的 `internal` 拿到的是这个 cascaded loader。`node:path.win32.isAbsolute` 与 `node:util.inherits` 与 Node 一致,其余 `win32` 成员抛出。`node:util` 的 JSON 数据比较器检查可枚举的自有属性,使 `__proto__` 等记录字段的准入判定与 Node 一致。全局 `process` shim 带有包括 `title` 在内的 Node 环境识别字段,避免 Worker 执行误入仅适用于 DOM 的分支;镜像中加载的包通过 Node 的 `global` 别名访问同一个 `globalThis` 对象。pack 期解析器会把名称静态可知的模块请求报告给 packer 的可达性遍历,其中包括通过 `node:module` 或 `module` 具名导入在模块作用域直接发起的 `createRequire(import.meta.url)('pkg')` 调用。保存、经 CommonJS 获取或另设基准的 `createRequire` 调用需要镜像入口种子。降低后的模块体在每次引用具名导入与 default 导入时,都经所 require 的模块对象读取,因此循环导入中的模块能在导出方完成初始化后读到该绑定;在含此类导入的模块中,对导入绑定赋值、直接调用 `eval`、声明使用保留前缀 `__dsh$` 的名字,都会使 pack 失败。VFS mutation 驱动 `node:fs` 的 callback、polling 和 promise watcher,监听回调运行在创建 watcher 时的异步上下文中,而不是写入方代码的上下文中;打开的 descriptor 在 rename、replacement 和 unlink 后仍保留文件身份与访问模式,只要文件名仍指向该文件,`FileHandle.stat({ bigint: true })` 报告的 device 与 inode 身份就与路径 stat 相同,`FileHandle.chmod()` 则更新打开文件身份的权限;`readable-stream` 提供 `node:stream/promises` 的完成等待与管道方法,以及文件流以及 Chokidar、readdirp 等未修改镜像包所用的流状态机。维护中的 `string_decoder` 包提供 `node:string_decoder`,在数据块之间保留不完整的多字节字符。AsyncLocalStorage 经 pack 时降低注入的 snapshot/restore 面在 `await` 间携带同步栈因果。worker 不带编译器:packer 未降低的镜像在挂载时被拒。回调式 `fs.realpath.native` 别名在已挂载的 VFS 内解析路径,并支持 `util.promisify`。 - **`src/shell/`(worker 自己的进程层)**——浏览器 worker 无法 fork,所以 `node:child_process` 不是 stub 而是实现:`spawn` 把命令放进它自己的 Web Worker——就是这同一个束,由首帧告诉它「你是 shell 进程」——并以 subprocess 服务消费的 `ChildProcess` 面报告结果。命令不占宿主线程,`SIGKILL` 不管它在干什么都能终止它,而它只能靠消息触达 VFS(由宿主应答这些帧)。Worker 平台 executable 在不替换 JavaScript 包、也不把具体实现耦合进 `node:child_process` 的情况下保持 Landlock 等 native 包协议;`xdg-open` 把一个 VFS 文本文件交给页面的只读查看器,因此 **打开配置文件** 等桌面打开操作会在页面内显示该文件;普通命令使用本包的求值器与 coreutils 命令表。语法来自 `@yarnpkg/parsers` 的 `parseShell`,而 `execSync`/`fork` 依然拒绝,因为它们需要真进程。 -- **`lib/client.js`(页面半)**——启动分为相互独立的两段。`chooseWorkerHostSource({ image?, fixtureManifest? })` 可选地拥有 boot barrier 与 fixture manifest:没有 `preview-fixture` 时停在来源选择面板,合法 query 则直接选择;两条路径都返回按序排列的 overlays。`connectWorkerHost(worker, { image?, overlays? })` 仍是公开的基础运行态连接器;调用方跳过选择器时 overlay 列表为空。`apps/web` 调用这两段并提供静态打包的 Worker。开局 `init` 帧携带基础镜像与按序排列的 overlay URL,boot 载荷送达结构化 index 注入表,`applyIndexInjections` 在壳入口运行前逐行执行。脚本 preload 行只是提示,因此会被跳过:`/plugins` 资源只能经 tunnel 解析,`loadBundle` 会在首次需要时获取 combo、把仅 tunnel 可达的 sourcemap 内嵌为 Base64 data URL,再以 Blob 执行脚本。在 shell 入口运行之前,页面读取 `GET /__assets__`(隧道以镜像中所有包资源组成的未压缩 tar 回答),并提供 `resolveAsset`,把 bundle 传给 `require.asset` 的每个 `plugins//assets/` 引用映射为这些字节的 Blob URL。worker 主动发出的 `view-text` 帧会打开页面的模态文本查看器。Tunnel 还暴露 fetch 形式的传输、独立文件上传载体和 API 客户端。请求帧通过结构化克隆保留 Blob 请求体,并转移 `ReadableStream` 的所有权。Host Worker 将两种请求体都逐块送入路由,因此通用文件上传不会在任何浏览器线程创建完整字节数组。Remote 流的上行以 `stream-uplink-item` / `stream-uplink-end` 帧进入没有上限的 `TunnelUplink`,`end` 之后到达的项被丢弃:页面与其 worker 是同一个可信的同源边界,Host 的 inbox 上限在此不适用。 +- **`lib/client.js`(页面半)**——启动分为相互独立的两段。`chooseWorkerHostSource({ image?, fixtureManifest? })` 可选地拥有 boot barrier 与 fixture manifest:没有 `preview-fixture` 时停在来源选择面板,合法 query 则直接选择;两条路径都返回按序排列的 overlays。manifest 中可选的 `links` 列表只接受相对 URL,显示在开始按钮旁;PR 预览工作流为它的 snapshot diff 页面加了一条。`connectWorkerHost(worker, { image?, overlays? })` 仍是公开的基础运行态连接器;调用方跳过选择器时 overlay 列表为空。`apps/web` 调用这两段并提供静态打包的 Worker。开局 `init` 帧携带基础镜像与按序排列的 overlay URL,boot 载荷送达结构化 index 注入表,`applyIndexInjections` 在壳入口运行前逐行执行。脚本 preload 行只是提示,因此会被跳过:`/plugins` 资源只能经 tunnel 解析,`loadBundle` 会在首次需要时获取 combo、把仅 tunnel 可达的 sourcemap 内嵌为 Base64 data URL,再以 Blob 执行脚本。在 shell 入口运行之前,页面读取 `GET /__assets__`(隧道以镜像中所有包资源组成的未压缩 tar 回答),并提供 `resolveAsset`,把 bundle 传给 `require.asset` 的每个 `plugins//assets/` 引用映射为这些字节的 Blob URL。worker 主动发出的 `view-text` 帧会打开页面的模态文本查看器。Tunnel 还暴露 fetch 形式的传输、独立文件上传载体和 API 客户端。请求帧通过结构化克隆保留 Blob 请求体,并转移 `ReadableStream` 的所有权。Host Worker 将两种请求体都逐块送入路由,因此通用文件上传不会在任何浏览器线程创建完整字节数组。Remote 流的上行以 `stream-uplink-item` / `stream-uplink-end` 帧进入没有上限的 `TunnelUplink`,`end` 之后到达的项被丢弃:页面与其 worker 是同一个可信的同源边界,Host 的 inbox 上限在此不适用。 在显式根上下文中登记的回调和定时器保留其空 store,避免继承无关事务。 diff --git a/packages/experimental/webworker-runtime/src/client/index.ts b/packages/experimental/webworker-runtime/src/client/index.ts index ab44c85d10..7366a56412 100644 --- a/packages/experimental/webworker-runtime/src/client/index.ts +++ b/packages/experimental/webworker-runtime/src/client/index.ts @@ -20,7 +20,7 @@ export { applyIndexInjections } from './apply-injections.ts' export { IMAGE_FILE_NAME } from '../image-layout.ts' export { parsePreviewFixtureManifest, PREVIEW_FIXTURE_MANIFEST_FILE, PREVIEW_FIXTURE_MANIFEST_VERSION, - type PreviewFixtureManifest, type PreviewFixtureManifestEntry, + type PreviewFixtureManifest, type PreviewFixtureManifestEntry, type PreviewLink, } from '../fixture-manifest.ts' /** Transport global the connection plugin reads instead of building an HTTP carrier. */ diff --git a/packages/experimental/webworker-runtime/src/client/source-chooser.ts b/packages/experimental/webworker-runtime/src/client/source-chooser.ts index 48d454eb94..95752bb84d 100644 --- a/packages/experimental/webworker-runtime/src/client/source-chooser.ts +++ b/packages/experimental/webworker-runtime/src/client/source-chooser.ts @@ -113,11 +113,23 @@ const CHOOSER_STYLE = ` font-size: 14px; line-height: 24px; } + [data-preview-source-footer] { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 12px 16px; + margin: 24px 0 0; + } + [data-preview-source-link] { + color: #61666b; + text-underline-offset: 3px; + } + [data-preview-source-link]:hover { color: #0f1115; } [data-preview-source-submit] { display: block; min-width: 120px; height: 36px; - margin: 24px 0 0 auto; + margin: 0 0 0 auto; padding: 0 14px; border: 0; border-radius: 18px; @@ -148,6 +160,8 @@ const CHOOSER_STYLE = ` [data-preview-source-option]:has(input:checked) { background: rgb(255 255 255 / 8%); } [data-preview-source-option]:has(input:checked) { border-color: rgb(255 255 255 / 12%); } [data-preview-source-option] input { accent-color: #f9fafb; } + [data-preview-source-link] { color: #cfd3d6; } + [data-preview-source-link]:hover { color: #f9fafb; } [data-preview-source-submit] { color: #0f1115; background: #f9fafb; } [data-preview-source-submit]:hover:not(:disabled) { background: #ebeef2; } [data-preview-source-submit]:focus-visible { outline-color: rgb(255 255 255 / 20%); } @@ -243,7 +257,10 @@ export async function choosePreviewSource(manifestUrl: URL): PromiseFilesystem source ${choices.map(choice => optionMarkup(choice, selected)).join('')} - +
+ ${manifest.links.map(link => `${escapeMarkup(link.label)}`).join('')} + +
` root.prepend(chooser) const form = chooser.querySelector('[data-preview-source-card]') diff --git a/packages/experimental/webworker-runtime/src/fixture-manifest.ts b/packages/experimental/webworker-runtime/src/fixture-manifest.ts index 7d2ecf2556..6d7804f727 100644 --- a/packages/experimental/webworker-runtime/src/fixture-manifest.ts +++ b/packages/experimental/webworker-runtime/src/fixture-manifest.ts @@ -14,12 +14,39 @@ export interface PreviewFixtureManifestEntry { readonly overlays: readonly string[] } +/** A page the source chooser links to, such as a report published beside the Preview. */ +export interface PreviewLink { + readonly label: string + /** URL resolved against the manifest URL; one that resolves to another origin is rejected. */ + readonly href: string +} + /** Complete built-in fixture catalog consumed before Worker startup. */ export interface PreviewFixtureManifest { readonly version: number /** Required default fixture id, or null when the chooser should default to an empty overlay. */ readonly defaultFixture: string | null readonly fixtures: readonly PreviewFixtureManifestEntry[] + /** Links shown on the source chooser; the parser reads an absent list as empty. */ + readonly links: readonly PreviewLink[] +} + +/** Resolving against this base shows whether an href could leave the manifest's origin. */ +const SAME_ORIGIN_PROBE = new URL('https://preview.invalid/') + +function parseLinks(value: unknown): PreviewLink[] { + if (value === undefined) return [] + if (!Array.isArray(value)) throw new Error('preview fixture manifest links must be an array') + return value.map((item) => { + const link = recordOf(item) + const label = link?.label + const href = link?.href + if (typeof label !== 'string' || label.length === 0 + || typeof href !== 'string' || href.length === 0 || new URL(href, SAME_ORIGIN_PROBE).origin !== SAME_ORIGIN_PROBE.origin) { + throw new Error('preview fixture manifest contains an invalid link') + } + return { label, href } + }) } function recordOf(value: unknown): Record | undefined { @@ -31,7 +58,7 @@ function recordOf(value: unknown): Record | undefined { /** * Validate the static fixture catalog before it controls Worker fetches. * @param value - Parsed JSON response. - * @returns A detached manifest with unique ids and non-empty overlay lists. + * @returns A detached manifest with unique ids, non-empty overlay lists, and relative links. */ export function parsePreviewFixtureManifest(value: unknown): PreviewFixtureManifest { const record = recordOf(value) @@ -64,5 +91,5 @@ export function parsePreviewFixtureManifest(value: unknown): PreviewFixtureManif if (defaultFixture !== null && (typeof defaultFixture !== 'string' || !ids.has(defaultFixture))) { throw new Error('preview fixture manifest defaultFixture does not name a fixture') } - return { version: PREVIEW_FIXTURE_MANIFEST_VERSION, defaultFixture, fixtures } + return { version: PREVIEW_FIXTURE_MANIFEST_VERSION, defaultFixture, fixtures, links: parseLinks(record.links) } } diff --git a/packages/experimental/webworker-runtime/src/index.ts b/packages/experimental/webworker-runtime/src/index.ts index c8d8907d3a..788120c22d 100644 --- a/packages/experimental/webworker-runtime/src/index.ts +++ b/packages/experimental/webworker-runtime/src/index.ts @@ -43,7 +43,7 @@ export { } from './image-manifest.ts' export { parsePreviewFixtureManifest, PREVIEW_FIXTURE_MANIFEST_FILE, PREVIEW_FIXTURE_MANIFEST_VERSION, - type PreviewFixtureManifest, type PreviewFixtureManifestEntry, + type PreviewFixtureManifest, type PreviewFixtureManifestEntry, type PreviewLink, } from './fixture-manifest.ts' export { loadVfsImage, loadVfsOverlay, MemoryVfs } from './storage/memory.ts' export { inflateImage, inflateImageStream } from './storage/image-gzip.ts' diff --git a/packages/experimental/webworker-runtime/tests/client/source-chooser.spec.ts b/packages/experimental/webworker-runtime/tests/client/source-chooser.spec.ts index f636c32ebe..14ded4eea2 100644 --- a/packages/experimental/webworker-runtime/tests/client/source-chooser.spec.ts +++ b/packages/experimental/webworker-runtime/tests/client/source-chooser.spec.ts @@ -15,6 +15,7 @@ const MANIFEST: PreviewFixtureManifest = { description: 'A deterministic example.', overlays: ['fixtures/base.tar.gz', 'fixtures/tail.tar.gz'], }], + links: [], } function setLocation(search = ''): void { @@ -108,6 +109,31 @@ describe('Preview source chooser', () => { expect(document.querySelector('[data-preview-source-style]')).toBeNull() }) + it('shows manifest links resolved against the manifest URL', async () => { + installManifest({ ...MANIFEST, links: [{ label: 'Snapshot ', href: '../snapshot-diff/' }] }) + + const selected = choosePreviewSource(MANIFEST_URL) + await vi.waitFor(() => { + expect(document.querySelector('[data-preview-source-link]')).not.toBeNull() + }) + const link = document.querySelector('[data-preview-source-link]') + expect([link?.textContent, link?.href]).toEqual(['Snapshot ', 'https://preview.test/snapshot-diff/']) + submitChooser() + await selected + }) + + it('shows no link when the manifest has none', async () => { + installManifest() + + const selected = choosePreviewSource(MANIFEST_URL) + await vi.waitFor(() => { + expect(document.querySelector('[data-preview-source-chooser]')).not.toBeNull() + }) + expect(document.querySelector('[data-preview-source-link]')).toBeNull() + submitChooser() + await selected + }) + it('selects the empty source when the manifest has no default', async () => { installManifest({ ...MANIFEST, defaultFixture: null }) diff --git a/packages/experimental/webworker-runtime/tests/fixture-manifest.spec.ts b/packages/experimental/webworker-runtime/tests/fixture-manifest.spec.ts index 01b3d00e9a..804f0e7dbd 100644 --- a/packages/experimental/webworker-runtime/tests/fixture-manifest.spec.ts +++ b/packages/experimental/webworker-runtime/tests/fixture-manifest.spec.ts @@ -23,9 +23,20 @@ describe('Preview fixture manifest', () => { description: 'A deterministic example.', overlays: ['fixtures/base.tar.gz', 'fixtures/tail.tar.gz'], }], + links: [], }) }) + it('accepts relative links', () => { + const links = [{ label: 'Snapshot changes', href: '../snapshot-diff/' }, { label: 'Root', href: '/report/' }] + expect(parsePreviewFixtureManifest({ version: 1, defaultFixture: null, fixtures: [], links }).links).toEqual(links) + }) + + it.each(['https://example.test/', 'javascript:alert(1)', '//example.test/', '\\\\example.test/', '', ' //evil.test/x', '/\t/evil.test/x', '\njavascript:alert(1)'])('rejects the link href %j', (href) => { + expect(() => parsePreviewFixtureManifest({ version: 1, defaultFixture: null, fixtures: [], links: [{ label: 'L', href }] })) + .toThrow(/invalid link/) + }) + it.each([ [{ version: 2, defaultFixture: null, fixtures: [] }, /must use version/], [{ version: 1, defaultFixture: 'missing', fixtures: [] }, /defaultFixture/], @@ -42,6 +53,8 @@ describe('Preview fixture manifest', () => { defaultFixture: 'none', fixtures: [{ id: 'none', label: 'None', description: 'Reserved.', overlays: ['none.tar.gz'] }], }, /invalid fixture entry/], + [{ version: 1, defaultFixture: null, fixtures: [], links: {} }, /links must be an array/], + [{ version: 1, defaultFixture: null, fixtures: [], links: [{ label: '', href: 'a/' }] }, /invalid link/], ])('rejects malformed catalogs', (value, error) => { expect(() => parsePreviewFixtureManifest(value)).toThrow(error) }) diff --git a/scripts/preview-workflow.spec.ts b/scripts/preview-workflow.spec.ts index bd21bc2c0a..b7c851c3eb 100644 --- a/scripts/preview-workflow.spec.ts +++ b/scripts/preview-workflow.spec.ts @@ -30,14 +30,15 @@ describe('PR preview workflow', () => { it('fails the check only for build failures and warns about publication', () => { const byName = (name: string) => preview.steps.find(step => step.name === name) - for (const name of ['Build workspace and check aggregate programs', 'Build the preview page and pack the VFS image', 'Shape the upload', 'Render the snapshot diff page']) { + for (const name of ['Build workspace and check aggregate programs', 'Build the preview page and pack the VFS image', 'Shape the upload']) { expect(byName(name)?.['continue-on-error'], `${name} must stay blocking`).toBeUndefined() } - for (const name of ['Upload to Cloudflare Pages', 'Verify the protected deployment serves the image', 'Comment the preview URL']) { + for (const name of ['Render the snapshot diff page', 'Upload to Cloudflare Pages', 'Verify the protected deployment serves the image', 'Comment the preview URL']) { expect(byName(name)?.['continue-on-error'], `${name} must warn instead of failing`).toBe(true) } const report = byName('Report preview publication failures') - expect(report?.if).toBe("steps.upload.outcome == 'failure' || steps.verify.outcome == 'failure' || steps.comment.outcome == 'failure'") + expect(report?.if).toBe("steps.snapshot-diff.outcome == 'failure' || steps.upload.outcome == 'failure'" + + " || steps.verify.outcome == 'failure' || steps.comment.outcome == 'failure'") expect(report?.run).toContain('::warning::') }) @@ -78,15 +79,19 @@ describe('PR preview workflow', () => { expect(verify.env?.CF_ACCESS_CLIENT_SECRET).toBe('${{ secrets.CF_ACCESS_CLIENT_SECRET }}') const comment = preview.steps.find(step => step.name === 'Comment the preview URL')! expect(comment.run).toContain('') - expect(comment.run).toContain('gh pr comment "$PR" --body-file -') + expect(comment.run).toContain('printf \'%s\' "$body" | gh pr comment "$PR" --body-file -') expect(comment.run).toContain('[snapshot changes]($url/snapshot-diff/)') + expect(comment.env?.SNAPSHOT_DIFF).toBe('${{ steps.snapshot-diff.outcome }}') + expect(comment.run).toContain('if [ "$SNAPSHOT_DIFF" = success ]') expect(comment.run).toContain('gh api -X PATCH') + expect(comment.run).toContain('select(.user.login == \\"github-actions[bot]\\"') }) it('renders the snapshot diff page into the upload against the base branch tip', () => { const steps = preview.steps.map(step => step.name) const page = preview.steps.find(step => step.name === 'Render the snapshot diff page')! - expect(page.run).toBe('pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD --out apps/web/dist/snapshot-diff/index.html') + expect(page.run).toBe('pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD' + + ' --out apps/web/dist/snapshot-diff/index.html --preview-manifest apps/web/dist/preview/fixtures.json') expect(steps.indexOf('Render the snapshot diff page')).toBeGreaterThan(steps.indexOf('Shape the upload')) expect(steps.indexOf('Render the snapshot diff page')).toBeLessThan(steps.indexOf('Upload to Cloudflare Pages')) }) diff --git a/scripts/snapshot-diff-page.spec.ts b/scripts/snapshot-diff-page.spec.ts index 5147ec6dd0..84ffd1dfff 100644 --- a/scripts/snapshot-diff-page.spec.ts +++ b/scripts/snapshot-diff-page.spec.ts @@ -1,7 +1,5 @@ import { describe, expect, it } from 'vitest' -import { groupDiffs, parseUnifiedDiff, renderSnapshotDiffPage } from './snapshot-diff-page.ts' - -const limits = { fileLines: 100, totalChars: 10_000 } +import { addPreviewLink, catalogFiles, groupDiffs, limitDiffs, parseUnifiedDiff, renderSnapshotDiffPage } from './snapshot-diff-page.ts' const diff = `diff --git a/snapshots/sdk/text-turn/system-prompt.expected.md b/snapshots/sdk/text-turn/system-prompt.expected.md index 1111111..2222222 100644 @@ -27,50 +25,80 @@ old mode 100644 new mode 100755 ` -const catalog = ['snapshots/sdk/text-turn/system-prompt.expected.md', 'snapshots/session/text-turn/tool-schemas.expected.json'] +const file = (path: string, hunks = '') => ({ path, hunks, binary: false, omitted: 0 }) describe('snapshot diff page', () => { it('splits git diff output into files with their hunks', () => { - expect(parseUnifiedDiff(diff, limits)).toEqual([ - { path: 'snapshots/sdk/text-turn/system-prompt.expected.md', hunks: '@@ -1,2 +1,2 @@\n You are an agent.\n-Old rule.\n+New rule.', binary: false, omitted: 0 }, - { path: 'snapshots/web/ptc-round/session.jsonl', hunks: '@@ -1 +0,0 @@\n-{"type":"header"}', binary: false, omitted: 0 }, - { path: 'snapshots/web/ptc-round/image.png', hunks: '', binary: true, omitted: 0 }, - { path: 'snapshots/web/present/workspace.expected/a b/说明.txt', hunks: '', binary: false, omitted: 0 }, + expect(parseUnifiedDiff(diff)).toEqual([ + file('snapshots/sdk/text-turn/system-prompt.expected.md', '@@ -1,2 +1,2 @@\n You are an agent.\n-Old rule.\n+New rule.'), + file('snapshots/web/ptc-round/session.jsonl', '@@ -1 +0,0 @@\n-{"type":"header"}'), + { ...file('snapshots/web/ptc-round/image.png'), binary: true }, + file('snapshots/web/present/workspace.expected/a b/说明.txt'), ]) - expect(parseUnifiedDiff('', limits)).toEqual([]) + expect(parseUnifiedDiff('')).toEqual([]) }) - it('rejects paths git still quotes', () => { - expect(() => parseUnifiedDiff('diff --git "a/snapshots/x\\ty" "b/snapshots/x\\ty"\n', limits)).toThrow('unsupported quoted path') + it.each([ + ['a quoted path', 'diff --git "a/snapshots/x\\ty" "b/snapshots/x\\ty"\n'], + ['unequal header paths', 'diff --git a/snapshots/x b/snapshots/y\n'], + ['a missing prefix', 'diff --git snapshots/x snapshots/x\n'], + ])('rejects a header with %s', (_, text) => { + expect(() => parseUnifiedDiff(text)).toThrow('unsupported git diff header') }) - it('truncates long files and drops hunks once the total budget is spent', () => { - const section = (name: string, lines: number) => `diff --git a/${name} b/${name}\n--- a/${name}\n+++ b/${name}\n@@ -1,${lines} +1,${lines} @@\n${'+x\n'.repeat(lines - 1)}` - const [long, fits, over] = parseUnifiedDiff(section('a', 150) + section('b', 10) + section('c', 10), { fileLines: 100, totalChars: 365 }) - expect([long!.hunks.split('\n').length, long!.omitted]).toEqual([100, 50]) - expect([fits!.hunks.split('\n').length, fits!.omitted]).toEqual([10, 0]) - expect([over!.hunks, over!.omitted]).toEqual(['', 10]) + it('truncates long sections and drops sections past the byte budget of the escaped JSON', () => { + const lines = (count: number, line = '+x') => file(`f${count}`, ['@@', ...Array.from({ length: count - 1 }, () => line)].join('\n')) + const [long, fits, over] = limitDiffs([lines(150), lines(10), lines(10)], { fileLines: 100, totalBytes: 445 }) + expect([long?.hunks.split('\n').length, long?.omitted]).toEqual([100, 50]) + expect([fits?.hunks.split('\n').length, fits?.omitted]).toEqual([10, 0]) + expect([over?.hunks, over?.omitted]).toEqual(['', 10]) + // Quotes, `@@`, and nine lines of an escaped newline, `+`, and two six-byte \u003c escapes: 139 bytes. + expect(limitDiffs([lines(10, '+<<')], { fileLines: 100, totalBytes: 138 })[0]?.omitted).toBe(10) + expect(limitDiffs([lines(10, '+<<')], { fileLines: 100, totalBytes: 139 })[0]?.omitted).toBe(0) }) - it('opens on the catalog, listing unchanged catalog files, then groups by scenario', () => { - const groups = groupDiffs(parseUnifiedDiff(diff, limits).slice(0, 3), catalog) - expect(groups.map(group => [group.title, group.paths, group.files.map(file => file.path)])).toEqual([ - ['SDK blank Session catalog', catalog, ['snapshots/sdk/text-turn/system-prompt.expected.md']], - ['sdk/text-turn', ['snapshots/sdk/text-turn/system-prompt.expected.md'], ['snapshots/sdk/text-turn/system-prompt.expected.md']], - ['web/ptc-round', ['snapshots/web/ptc-round/image.png', 'snapshots/web/ptc-round/session.jsonl'], ['snapshots/web/ptc-round/image.png', 'snapshots/web/ptc-round/session.jsonl']], + it('opens on the catalog, then groups scenarios and other files by directory in code point order', () => { + const catalog = ['snapshots/sdk/text-turn/system-prompt.expected.md', 'snapshots/session/text-turn/tool-schemas.expected.json'] + const paths = ['snapshots/web/b/x', 'snapshots/sdk/sdk.snapshot.ts', 'snapshots/AGENTS.md', 'snapshots/web/B/x', 'snapshots/web/b/a/y'] + expect(groupDiffs([...paths, 'snapshots/web/b/x'].map(path => file(path)), catalog)).toEqual([ + { title: 'SDK blank Session catalog', paths: catalog }, + { title: 'snapshots', paths: ['snapshots/AGENTS.md'] }, + { title: 'sdk', paths: ['snapshots/sdk/sdk.snapshot.ts'] }, + { title: 'web/B', paths: ['snapshots/web/B/x'] }, + { title: 'web/b', paths: ['snapshots/web/b/a/y', 'snapshots/web/b/x'] }, ]) }) - it('lists a path once when a type change splits it into two sections', () => { - const removed = { path: 'snapshots/acp/cancel/system-prompt.expected.md', hunks: '@@ -1 +0,0 @@\n-../x', binary: false, omitted: 0 } - const added = { ...removed, hunks: '@@ -0,0 +1 @@\n+text' } - expect(groupDiffs([removed, added], catalog)[1]).toEqual({ title: 'acp/cancel', paths: [removed.path], files: [removed, added] }) + it.each([ + ['owns both sidecars', 'profile: sdk\n', 'sdk/text-turn', 'sdk/text-turn'], + ['names a source in its own suite directory', 'profile: sdk-minimal\nheader:\n toolSchemasSource: other\n', 'sdk/text-turn', 'sdk/other'], + ['names sources in another suite', 'profile: sdk\nheader:\n systemPromptSource: session/a\n toolSchemasSource: session/b\n', 'session/a', 'session/b'], + ])('resolves catalog sidecars when the manifest %s', (_, text, prompt, schemas) => { + expect(catalogFiles(text)).toEqual({ + systemPrompt: `snapshots/${prompt}/system-prompt.expected.md`, + toolSchemas: `snapshots/${schemas}/tool-schemas.expected.json`, + }) + }) + + it.each([ + ['a non-string source', 'profile: sdk\nheader:\n toolSchemasSource: 1\n', 'header.toolSchemasSource must be a non-empty string'], + ['an empty source', 'header:\n systemPromptSource: ""\n', 'header.systemPromptSource must be a non-empty string'], + ])('rejects %s', (_, text, message) => { + expect(() => catalogFiles(text)).toThrow(message) }) it('embeds the data so diff text cannot close the script element', () => { - const page = renderSnapshotDiffPage([{ title: 't', paths: ['p'], files: [{ path: 'p', hunks: '+', binary: false, omitted: 0 }] }], 'a → b') + const files = [file('p', '+')] + const page = renderSnapshotDiffPage(files, [{ title: 't', paths: ['p'] }], 'a → b') expect(page).not.toContain('') - const data = /', binary: false, omitted: 0 }] }], heading: 'a → b' }) + const data = / ')] - const page = renderSnapshotDiffPage(files, [{ title: 't', paths: ['p'] }], 'a → b') + it('embeds the index so a path cannot close the script element', () => { + const files = [{ path: 'p', added: 1, removed: 0 }] + const groups = [{ title: 't', paths: ['p'] }] + const page = renderSnapshotDiffPage(files, groups, 'a → b') expect(page).not.toContain('') const data = /')) } - // An authenticated browser renders for the owner's shared browser Peer. - expect(renderedFor).toEqual([loaded.connection.browserPeer, loaded.connection.browserPeer, loaded.connection.browserPeer]) + // Default-token requests render for the Peer owned by the token provider. + const admission = loaded.connection.authentication.authenticate({ headers: { host: `127.0.0.1:${String(port)}`, cookie } }) + if ('rejection' in admission) throw new Error('token provider refused its issued Cookie') + expect(admission.peer).not.toBe(loaded.connection.browserPeer) + expect(renderedFor).toEqual([admission.peer, admission.peer, admission.peer, admission.peer]) offRows() expect(await request(port, '/', authenticated({ method: 'HEAD' }))).toEqual({ status: 200, @@ -230,10 +261,95 @@ describe('real Loader composition', () => { expect(() => server.registerFallback(() => {})).not.toThrow() }) + it('uses centralized HTTP admission while public files and in-process reads stay independent', { timeout: 60_000 }, async () => { + const loaded = await loadComposition() + const reader = loaded.connection.createPeer({ principal: { kind: 'owner' } }) + let attempts = 0 + loaded.connection.authentication.register({ authenticate() { + attempts++ + return undefined + } }) + for (const path of ['/app.js', '/preview.html', '/missing.js', '/..%2f..%2foutside']) await request(loaded.webServer.port, path) + expect(attempts).toBe(0) + const inProcess = await loaded.webServer.readResource(new Request('http://reader.invalid/'), reader) + await inProcess.text() + expect(attempts).toBe(0) + expect((await request(loaded.webServer.port, '/')).status).toBe(401) + expect(attempts).toBe(1) + expect((await request(loaded.webServer.port, '/index.html', { method: 'HEAD' })).status).toBe(401) + expect(attempts).toBe(2) + }) + + it('renders each HTTP index for the Peer returned by page admission', { timeout: 60_000 }, async () => { + const loaded = await loadComposition() + const reader = loaded.connection.createPeer({ principal: { kind: 'owner' }, interactions: 'none' }) + expect(reader).not.toBe(loaded.connection.browserPeer) + let attempts = 0 + const unregister = loaded.connection.authentication.register({ + authenticate(input) { + attempts++ + const value = input.headers instanceof Headers ? input.headers.get('x-reader') : input.headers['x-reader'] + return value === 'external' ? reader : undefined + }, + }) + const renderedFor: Connection.PeerScope[] = [] + loaded.on('webserver/index-inject', (rows, peer) => { + renderedFor.push(peer) + rows.push({ kind: 'global', name: '__READER__', value: peer === reader }) + }) + for (const path of ['/', '/index.html']) { + const response = await request(loaded.webServer.port, path, { headers: { 'x-reader': 'external' } }) + expect(response.status).toBe(200) + expect(response.body).toContain('globalThis["__READER__"] = true') + } + expect(renderedFor).toEqual([reader, reader]) + expect(attempts).toBe(2) + await unregister() + expect((await request(loaded.webServer.port, '/', { headers: { 'x-reader': 'external' } })).status).toBe(401) + }) + + it('reports unavailable authentication without rendering the index', async () => { + const loaded = await loadComposition() + loaded.connection.authentication.register({ authenticate() { throw new Error('provider unavailable') } }) + const rendered = vi.fn() + loaded.on('webserver/index-inject', rendered) + for (const path of ['/', '/index.html']) { + expect(await request(loaded.webServer.port, path)).toMatchObject({ status: 503, body: 'authentication unavailable' }) + expect(await request(loaded.webServer.port, path, { method: 'HEAD' })).toMatchObject({ status: 503, body: '' }) + } + expect(rendered).not.toHaveBeenCalled() + }) + + it.each(['request', 'peer'] as const)('does not inject an index after its %s ends during file reading', { timeout: 60_000 }, async (ended) => { + const loaded = await loadComposition() + const reader = loaded.connection.createPeer({ principal: { kind: 'owner' } }) + const controller = new AbortController() + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + heldIndex.path = join(root!, 'dist', 'index.html') + heldIndex.entered = () => { entered.resolve(undefined) } + heldIndex.release = release.promise + const renderedFor: Connection.PeerScope[] = [] + loaded.on('webserver/index-inject', (_rows, peer) => { renderedFor.push(peer) }) + const result = loaded.webServer.readResource(new Request('http://reader.invalid/', { signal: controller.signal }), reader) + const outcome = result.then(() => 'served', () => 'cancelled') + try { + await entered.promise + if (ended === 'request') controller.abort() + else await reader.dispose() + release.resolve(undefined) + expect(await outcome).toBe('cancelled') + expect(renderedFor).toEqual([]) + } finally { + release.resolve(undefined) + await outcome + } + }) + it('answers in-process reads for the given Peer without browser authentication', { timeout: 60_000 }, async () => { const loaded = await loadComposition() const server = loaded.webServer - const reader = { principal: { kind: 'owner' } } as Connection.PeerScope + const reader = loaded.connection.createPeer({ principal: { kind: 'owner' } }) const read = (path: string, init?: RequestInit) => server.readResource(new Request(`http://reader.invalid${path}`, init), reader) const renderedFor: Connection.PeerScope[] = [] loaded.on('webserver/index-inject', (rows, peer) => { @@ -283,7 +399,7 @@ describe('real Loader composition', () => { expect([revalidated.status, revalidated.headers.get('etag'), revalidated.headers.get('cache-control')]).toEqual([304, etag, 'no-cache']) expect(await revalidated.text()).toBe('') // An in-process read revalidates the same way. - const reader = { principal: { kind: 'owner' } } as Connection.PeerScope + const reader = loaded.connection.createPeer({ principal: { kind: 'owner' } }) const read = await loaded.webServer.readResource(new Request(`${base}/app.js`, { headers: { 'if-none-match': etag } }), reader) expect(read.status).toBe(304) diff --git a/packages/host/open-in-app/README.i18n.yaml b/packages/host/open-in-app/README.i18n.yaml index 97f08b56d1..8b7437f949 100644 --- a/packages/host/open-in-app/README.i18n.yaml +++ b/packages/host/open-in-app/README.i18n.yaml @@ -9,14 +9,14 @@ en: 91ff0fbf5f0b95b9 zh: 13a18d1a9bc38da0 /deepseek-ai-dsh-host-open-in-app/summary: - en: 894ed6d5eec55b71 - zh: b94ae1411966f145 + en: f6922aa70b598d29 + zh: d03dafb50850fafc /deepseek-ai-dsh-host-open-in-app/table-of-contents: en: d152484eb41ac6b4 zh: 725b47765ee8f30b /deepseek-ai-dsh-host-open-in-app/use-this-package: - en: c1217da1d6bdfd36 - zh: cbb05caa1a7764d0 + en: b800b5c32358b04f + zh: b7df359af6cd4c47 /deepseek-ai-dsh-host-open-in-app/use-this-package/when-to-choose-it: en: fcf8f52b6cf1f0dd zh: aed2366ccd0f112a @@ -33,8 +33,8 @@ en: 558e741770080c93 zh: 80482d355dc89cae /deepseek-ai-dsh-host-open-in-app/understand-the-implementation: - en: 0ebb9f5dfb251f11 - zh: d60bd93d5b3e6fb9 + en: 2245b83097ae2e1b + zh: 306ec4b3edfa3e47 /deepseek-ai-dsh-host-open-in-app/further-exploration: en: d5b6ee9a195a810b zh: 7825d6182be37255 diff --git a/packages/host/open-in-app/README.md b/packages/host/open-in-app/README.md index d32d42b93a..df763084c7 100644 --- a/packages/host/open-in-app/README.md +++ b/packages/host/open-in-app/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Use `dsh-host-open-in-app` with its [browser companion](../../client/ui-open-in-app/README.md) to let users open a workspace directory in an installed editor, Git GUI, terminal, or file manager. It offers a fixed application catalog and shows only entries that the host can verify; newly installed applications appear after restart, while missing launchers are removed when detected. Requests require the deployment's browser authentication and host-origin trust checks. Detection and launch commands use configurable deadlines and do not pass inherited credentials to launched applications. +Use `dsh-host-open-in-app` with its [browser companion](../../client/ui-open-in-app/README.md) to let users open a workspace directory in an installed editor, Git GUI, terminal, or file manager. It offers a fixed application catalog and shows only entries that the host can verify; newly installed applications appear after restart, while missing launchers are removed when detected. Requests require WebServer admission and an owner Peer; non-owner Peers receive 403 before application probing, icon access, or launch. Detection and launch commands use configurable deadlines and do not pass inherited credentials to launched applications. ## Table of Contents @@ -25,7 +25,7 @@ Use `dsh-host-open-in-app` with its [browser companion](../../client/ui-open-in- ## Use this package -Mount the package in a composition that carries `webServer`, `connection`, and `subprocess`, normally beside its browser surface [`dsh-client-ui-open-in-app`](../../client/ui-open-in-app/README.md); the pair puts an "Open In..." split button in the Web Session header whenever the host resolved at least one installed catalog application. +Mount the package in a composition that carries `webServer` and `subprocess`, normally beside its browser surface [`dsh-client-ui-open-in-app`](../../client/ui-open-in-app/README.md); the pair puts an "Open In..." split button in the Web Session header whenever the host resolved at least one installed catalog application. ### When to choose it @@ -79,7 +79,7 @@ Linux desktop-entry fields and icons use the shared [native-command](../../util/ The package splits into a data table and three roles. [`src/catalog.ts`](src/catalog.ts) is the compile-time table: each entry's per-platform locator chain (`fixed`, `app`, `xcode`, `cli`, `file`, `scan`, `app-paths`, `install-record`, `github-desktop`, `desktop`) plus, on Linux, the desktop-entry id owning its icon. [`src/resolver.ts`](src/resolver.ts) resolves the table against this host: one pass yields a map of catalog id to verified launch (primary and optional fallback argv plus the icon source), sharing one batched Windows-registry read; argv launches spawn detached with a credential-scrubbed environment (`scrubbedParentEnv`) minus the Desktop Host's `ELECTRON_RUN_AS_NODE`, plus explicit adapter entries, and keep Windows GUI processes visible unless the adapter hides a CLI process that launches the GUI separately. `shell-open` launches (the file managers) run the OS shell's open verb through `dsh-native-command`'s path opener under the same watch window, and a spawn `ENOENT` is classified as `missing` so the routes can refresh a stale entry. [`src/icons.ts`](src/icons.ts) extracts icons per platform: `plutil`/`sips` over the resolved bundle on macOS, a generated PowerShell `ExtractAssociatedIcon` script over the resolved executable on Windows (positional `-File` args keep paths out of command-line parsing), and desktop-entry/hicolor/pixmaps filesystem lookup on Linux. -[`src/index.ts`](src/index.ts) registers the three routes on `ctx.webServer`: `GET /open-in-app/apps` (the resolution map's keys), `GET /open-in-app/icon/` (the extracted icon, cached in memory per process), and `POST /open-in-app/open` (launches the map's verified launcher directly — never a re-detection). Every route asks the composition's `connection` service for a rejection first; the complete trust story — the Host/Origin fence and browser authentication — has one home in the [`src/index.ts`](src/index.ts) module comment. On top of that fence the open route validates its body at the wire: an `application/json` media type, a 64 KiB ceiling, a resolved-available catalog id, and an absolute path naming an existing directory. Resolution and icon commands run through [`@deepseek-ai/dsh-native-command`](../../util/native-command/README.md) (argv, never a shell) under their respective deadlines; PATH names go through `ctx.subprocess.resolveExecutable()` in-process. +[`src/index.ts`](src/index.ts) registers the three routes on `ctx.webServer`: `GET /open-in-app/apps` (the resolution map's keys), `GET /open-in-app/icon/` (the extracted icon, cached in memory per process), and `POST /open-in-app/open` (launches the map's verified launcher directly — never a re-detection). Every route declares required WebServer admission and checks the supplied Peer's owner principal before accessing Host resources. The open route also validates its body at the wire: an `application/json` media type, a 64 KiB ceiling, a resolved-available catalog id, and an absolute path naming an existing directory. Resolution and icon commands run through [`@deepseek-ai/dsh-native-command`](../../util/native-command/README.md) (argv, never a shell) under their respective deadlines; PATH names go through `ctx.subprocess.resolveExecutable()` in-process. diff --git a/packages/host/open-in-app/README.zh.md b/packages/host/open-in-app/README.zh.md index d14624c00d..3d4858c610 100644 --- a/packages/host/open-in-app/README.zh.md +++ b/packages/host/open-in-app/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -将 `dsh-host-open-in-app` 与其[浏览器配套包](../../client/ui-open-in-app/README.zh.md)一起使用,让用户能在已安装的编辑器、Git GUI、终端或文件管理器中打开 workspace 目录。本包提供固定的应用目录,并只显示主机能够验证的条目;新安装的应用在重启后出现,而检测到启动器缺失时会移除对应条目。请求须通过部署的浏览器认证与主机来源信任检查。检测与启动命令使用可配置的期限,且不会把继承的凭据传给启动的应用。 +将 `dsh-host-open-in-app` 与其[浏览器配套包](../../client/ui-open-in-app/README.zh.md)一起使用,让用户能在已安装的编辑器、Git GUI、终端或文件管理器中打开 workspace 目录。本包提供固定的应用目录,并只显示主机能够验证的条目;新安装的应用在重启后出现,而检测到启动器缺失时会移除对应条目。请求须通过 WebServer 准入并持有 owner Peer;非 owner Peer 在应用探测、图标访问或启动前收到403。检测与启动命令使用可配置的期限,且不会把继承的凭据传给启动的应用。 ## 目录 @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -把本包挂进携带 `webServer`、`connection` 与 `subprocess` 的组合,通常与其浏览器表面 [`dsh-client-ui-open-in-app`](../../client/ui-open-in-app/README.zh.md) 并排;只要主机解析出目录中至少一个已安装的应用,这对包就会在 Web 会话头部放上 "Open In..." 分体按钮。 +把本包挂进携带 `webServer` 与 `subprocess` 的组合,通常与其浏览器表面 [`dsh-client-ui-open-in-app`](../../client/ui-open-in-app/README.zh.md) 并排;只要主机解析出目录中至少一个已安装的应用,这对包就会在 Web 会话头部放上 "Open In..." 分体按钮。 ### 何时选择 @@ -79,7 +79,7 @@ Linux 桌面文件字段和图标使用共享的 [native-command](../../util/nat 本包拆为一张数据表与三个角色。[`src/catalog.ts`](src/catalog.ts) 是编译期表格:每个条目按平台的 locator 链(`fixed`、`app`、`xcode`、`cli`、`file`、`scan`、`app-paths`、`install-record`、`github-desktop`、`desktop`),以及 Linux 上拥有其图标的 desktop 条目 id。[`src/resolver.ts`](src/resolver.ts) 把表格解析到本机:一趟产出目录 id 到已验证启动的映射(主/回退 argv 加图标来源),共享一次批量的 Windows 注册表读取;argv 启动以清理过凭据的环境(`scrubbedParentEnv`)去掉 Desktop Host 的 `ELECTRON_RUN_AS_NODE` 后叠加适配器显式环境,再 detached 派生,Windows GUI 默认保持可见,只有负责另行打开 GUI 的 CLI 适配器会隐藏自己的进程。`shell-open` 启动(文件管理器)在同一看护窗口下经 `dsh-native-command` 的路径打开器执行 OS shell 的 open verb,spawn 的 `ENOENT` 被归类为 `missing`,让路由能刷新失效条目。[`src/icons.ts`](src/icons.ts) 按平台提取图标:macOS 在解析出的 bundle 上跑 `plutil`/`sips`,Windows 在解析出的可执行文件上跑生成的 PowerShell `ExtractAssociatedIcon` 脚本(`-File` 位置参数让路径不经过命令行解析),Linux 走 desktop 条目/hicolor/pixmaps 的文件系统查找。 -[`src/index.ts`](src/index.ts) 在 `ctx.webServer` 上注册三条路由:`GET /open-in-app/apps`(解析映射的 keys)、`GET /open-in-app/icon/`(提取的图标,进程内内存缓存)、`POST /open-in-app/open`(直接使用映射中已验证的启动器——绝不重新检测)。每条路由都先向组合的 `connection` 服务询问是否拒绝;完整的信任叙述——Host/Origin 栅栏与浏览器认证——唯一的出处在 [`src/index.ts`](src/index.ts) 的模块注释。在该栅栏之上,open 路由在 wire 边界校验请求体:`application/json` 媒体类型、64 KiB 上限、解析为可用的目录 id、指向现存目录的绝对路径。解析与图标命令经 [`@deepseek-ai/dsh-native-command`](../../util/native-command/README.zh.md)(argv,绝不走 shell)在各自期限内执行;PATH 名称走 `ctx.subprocess.resolveExecutable()` 进程内解析。 +[`src/index.ts`](src/index.ts) 在 `ctx.webServer` 上注册三条路由:`GET /open-in-app/apps`(解析映射的 keys)、`GET /open-in-app/icon/`(提取的图标,进程内内存缓存)、`POST /open-in-app/open`(直接使用映射中已验证的启动器——绝不重新检测)。每条路由均声明 WebServer 认证准入,并在访问 Host 资源前检查传入 Peer 的 owner principal。open 路由还在 wire 边界校验请求体:`application/json` 媒体类型、64 KiB 上限、解析为可用的目录 id、指向现存目录的绝对路径。解析与图标命令经 [`@deepseek-ai/dsh-native-command`](../../util/native-command/README.zh.md)(argv,绝不走 shell)在各自期限内执行;PATH 名称走 `ctx.subprocess.resolveExecutable()` 进程内解析。 diff --git a/packages/host/open-in-app/package.json b/packages/host/open-in-app/package.json index 256d6919a8..29ce84dcd0 100644 --- a/packages/host/open-in-app/package.json +++ b/packages/host/open-in-app/package.json @@ -52,6 +52,7 @@ "devDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/cordis-plugin-loader": "workspace:~", - "@deepseek-ai/dsh-host-webserver": "workspace:*" + "@deepseek-ai/dsh-host-webserver": "workspace:*", + "@deepseek-ai/dsh-typert-protocol": "workspace:*" } } diff --git a/packages/host/open-in-app/src/index.ts b/packages/host/open-in-app/src/index.ts index 8e8da91ec4..13baf80bae 100644 --- a/packages/host/open-in-app/src/index.ts +++ b/packages/host/open-in-app/src/index.ts @@ -4,12 +4,8 @@ * launch endpoint the browser split button * (`@deepseek-ai/dsh-client-ui-open-in-app`) posts to. * - * Security has one home, here. Every route asks the composition's - * `connection` service for a rejection first (`requestRejection`): its - * Host/Origin fence defeats DNS rebinding and cross-site calls, and its - * browser authentication (the login-token cookie) gates every caller before - * any resolution result, icon, or launch is reachable. On top of that fence - * the open route validates its body at the wire: an `application/json` media + * WebServer admits requests before dispatch; these routes require an owner Peer. + * The open route validates its body at the wire: an `application/json` media * type, a 64 KiB ceiling, string `app`/`path` fields, a resolved-available * catalog id, and an absolute path naming an existing directory. * @@ -43,8 +39,8 @@ export type * from './shared.ts' /** Cordis function-plugin name. */ export const name = 'open-in-app' -/** The route carrier, the trust fence guarding every route, and the PATH resolver. */ -export const inject = ['webServer', 'connection', 'subprocess'] +/** The route carrier and the PATH resolver. */ +export const inject = ['webServer', 'subprocess'] /** Open-in-app host configuration. */ export interface Config { @@ -75,16 +71,6 @@ export const Config: z = z.object({ launchWatchMs: boundedMs(), }) -/** Trust surface consumed here; the browser-side connection package owns the full type. */ -interface OpenInAppConnection { - requestRejection(request: { readonly headers: IncomingMessage['headers'] }): 401 | 403 | undefined -} - -/** The composition's connection service (typed locally: its package is browser-side). */ -function connectionOf(ctx: Context): OpenInAppConnection { - return Reflect.get(ctx, 'connection') as OpenInAppConnection -} - /** Open-route request bodies are tiny JSON objects; anything larger is hostile. */ const MAX_BODY_BYTES = 64 * 1024 @@ -134,7 +120,7 @@ function parseOpenBody(text: string): { app: string; path: string } | null { return typeof app === 'string' && typeof path === 'string' ? { app, path } : null } -/** Register the apps, icon, and open routes behind the connection trust fence. */ +/** Register owner-only apps, icon, and open routes. */ export function apply(ctx: Context, config: Config): void { const ssh = launchedThroughSsh(launchEnvironmentOf(ctx)) /** Test-seam facts completed with the composition's PATH resolver. */ @@ -181,20 +167,15 @@ export function apply(ctx: Context, config: Config): void { map.set(app.id, fresh) return fresh } - /** Answer an untrusted/unauthenticated request; true when it was rejected. */ - const rejected = (req: IncomingMessage, res: ServerResponse): boolean => { - const rejection = connectionOf(ctx).requestRejection(req) - if (rejection === undefined) return false - res.statusCode = rejection - res.end() - return true - } - ctx.effect(() => ctx.webServer.register({ kind: 'exact', + auth: 'required', path: OPEN_IN_APP_APPS_PATH, - handler: async (req, res) => { - if (rejected(req, res)) return + handler: async (req, res, peer) => { + if (peer?.principal.kind !== 'owner') { + sendJson(res, 403, { code: 'forbidden', message: 'owner access required' }) + return + } if (req.method !== 'GET') { sendMethodNotAllowed(res, 'GET') return @@ -205,9 +186,13 @@ export function apply(ctx: Context, config: Config): void { ctx.effect(() => ctx.webServer.register({ kind: 'prefix', + auth: 'required', path: OPEN_IN_APP_ICON_PREFIX_PATH, - handler: async (req, res) => { - if (rejected(req, res)) return + handler: async (req, res, peer) => { + if (peer?.principal.kind !== 'owner') { + sendJson(res, 403, { code: 'forbidden', message: 'owner access required' }) + return + } if (req.method !== 'GET') { sendMethodNotAllowed(res, 'GET') return @@ -240,9 +225,13 @@ export function apply(ctx: Context, config: Config): void { ctx.effect(() => ctx.webServer.register({ kind: 'exact', + auth: 'required', path: OPEN_IN_APP_OPEN_PATH, - handler: async (req, res) => { - if (rejected(req, res)) return + handler: async (req, res, peer) => { + if (peer?.principal.kind !== 'owner') { + sendJson(res, 403, { code: 'forbidden', message: 'owner access required' }) + return + } if (req.method !== 'POST') { sendMethodNotAllowed(res, 'POST') return diff --git a/packages/host/open-in-app/tests/host-routes.spec.ts b/packages/host/open-in-app/tests/host-routes.spec.ts index ff73819cc0..6327b3ff08 100644 --- a/packages/host/open-in-app/tests/host-routes.spec.ts +++ b/packages/host/open-in-app/tests/host-routes.spec.ts @@ -1,12 +1,11 @@ /** * Host routes over a real WebServer booted through the vendored Loader * (the REAL-composition requirement), asserting the HTTP surface: the - * connection trust fence, the one-pass catalog resolution the routes share, + * centralized admission, owner authorization, and one-pass catalog resolution, * icon serving with caching, the open route's wire validation, and the * stale-launcher (ENOENT) refresh. Host commands, launches, and PATH - * resolution are faked through the package `internals` seam; the connection - * service is a controllable stub (its real provider is the browser - * composition); the filesystem is real. + * resolution are faked through the package `internals` seam; admission returns + * a controllable Peer; the filesystem is real. */ import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' @@ -18,7 +17,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' -import WebServer from '@deepseek-ai/dsh-host-webserver' +import WebServer, { type WebRoute } from '@deepseek-ai/dsh-host-webserver' import type { NativeCommandRunner } from '@deepseek-ai/dsh-native-command' import { createLaunchEnvironmentSnapshot, DSH_LAUNCH_ENVIRONMENT_KEY, type LaunchEnvironmentLayerInput, @@ -27,9 +26,15 @@ import * as OpenInApp from '../src/index.ts' import { internals } from '../src/internals.ts' import type { OpenInAppLauncher } from '../src/resolver.ts' +declare module '@deepseek-ai/dsh-typert-protocol' { + interface PrincipalMap { + openInAppAuthorizationTest: { readonly kind: 'open-in-app-authorization-test' } + } +} + let root: string | undefined let context: Context | undefined -/** Answer the connection stub gives every route until a test changes it. */ +/** Central admission decision until a test changes it. */ const trust: { rejection: 401 | 403 | undefined } = { rejection: undefined } afterEach(async () => { @@ -48,7 +53,7 @@ function pathTable(entries: Record = {}): (name: string) => Prom } /** Boot webserver + open-in-app rows through the real Loader. */ -async function boot(layers: readonly LaunchEnvironmentLayerInput[] = []): Promise { +async function boot(layers: readonly LaunchEnvironmentLayerInput[] = [], access: 'owner' | 'restricted' = 'owner'): Promise { internals.catalog = { env: {}, ...internals.catalog } root = await mkdtemp(join(tmpdir(), 'dsh-open-in-app-loader-')) const configPath = join(root, 'cordis.yml') @@ -68,7 +73,17 @@ async function boot(layers: readonly LaunchEnvironmentLayerInput[] = []): Promis context = new Context() context.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot(layers)) context.baseUrl = pathToFileURL(root).href + '/' - context.provide('connection', { requestRejection: () => trust.rejection } as never) + type Peer = NonNullable[2]> + const abort = new AbortController() + const peer: Peer = { + id: 'open-in-app-fixture' as Peer['id'], ctx: context, + principal: access === 'owner' ? { kind: 'owner' } : { kind: 'open-in-app-authorization-test' }, + signal: abort.signal, interactions: 'none', dispose: async () => { abort.abort() }, + } + context.effect(() => () => peer.dispose()) + context.on('webserver/authorize', () => trust.rejection === undefined + ? { kind: 'allow', peer } + : { kind: 'deny', status: trust.rejection }) // The plugin resolves PATH names through the composition's subprocess // capability; the not-found rejection is the provider's real signal. context.provide('subprocess', { @@ -172,7 +187,7 @@ describe('open-in-app host routes (real Loader composition)', () => { expect(Object.keys(OpenInApp).sort()).toEqual(['Config', 'apply', 'inject', 'name']) }) - it('answers the connection rejection on every route, before any resolution runs', async () => { + it('answers the admission rejection on every route, before any resolution runs', async () => { const run = vi.fn() internals.catalog = { platform: 'darwin', run, resolveExecutable: pathTable() } const base = await boot() @@ -188,6 +203,31 @@ describe('open-in-app host routes (real Loader composition)', () => { expect((await fetch(`${base}/open-in-app/apps`)).status).toBe(200) }) + it('refuses an authenticated non-owner before probing, reading icons, or launching', async () => { + const run = vi.fn() + const launch = vi.fn() + const resolveExecutable = vi.fn(pathTable()) + internals.catalog = { platform: 'darwin', run, launch, resolveExecutable } + const base = await boot([], 'restricted') + expect(context?.get('connection')).toBeUndefined() + for (const [path, options] of [ + ['/open-in-app/apps', {}], + ['/open-in-app/icon/finder', {}], + ['/open-in-app/open', { + method: 'POST', headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ app: 'finder', path: root }), + }], + ] as const) { + const response = await fetch(`${base}${path}`, options) + expect(response.status).toBe(403) + expect(response.headers.get('cache-control')).toBe('no-store') + await response.text() + } + expect(run).not.toHaveBeenCalled() + expect(resolveExecutable).not.toHaveBeenCalled() + expect(launch).not.toHaveBeenCalled() + }) + it('serves the resolved catalog, one cached icon, and launches from the same resolution', async () => { const launches: string[][] = [] const home = await mkdtemp(join(tmpdir(), 'dsh-open-in-app-home-')) diff --git a/packages/host/webserver/README.i18n.yaml b/packages/host/webserver/README.i18n.yaml index 7a81b0a0db..ac210137e2 100644 --- a/packages/host/webserver/README.i18n.yaml +++ b/packages/host/webserver/README.i18n.yaml @@ -24,11 +24,11 @@ en: 90352948bfdc1d99 zh: 35d148bf3bfcf76f /deepseek-ai-dsh-host-webserver/use-this-package/registering-routes: - en: 55b5f5751c46e0ee - zh: 6c609104f0798e01 + en: cf35827f67a2b78f + zh: f2259e857335d48f /deepseek-ai-dsh-host-webserver/use-this-package/the-fallback-seat: - en: 20e5a88f42ba38aa - zh: f20d2f4b3eba267a + en: 6e9a37ec076c8f50 + zh: 1e7c2291c6af9e61 /deepseek-ai-dsh-host-webserver/use-this-package/behavior-under-failure: en: 1bfff905b600f694 zh: 73f3b7704af686dc @@ -36,8 +36,8 @@ en: 42b15ac6321706aa zh: 4ed0861911abaf5d /deepseek-ai-dsh-host-webserver/understand-the-implementation/design-concept: - en: 88adbd5967b978d3 - zh: b4fabfd6f5df1b71 + en: 66e4cf637f553ddf + zh: 47d6d5ea8f7c3ac8 /deepseek-ai-dsh-host-webserver/understand-the-implementation/matching-and-lifecycle: en: 8589aba0cbaa1c76 zh: babf3b27b0cdb35e @@ -54,8 +54,8 @@ en: ca75c51c89c2c9b0 zh: de54f3467ef3b9be /deepseek-ai-dsh-host-webserver/known-limitations-and-deferred-work: - en: 9aa6b8cf92d5b506 - zh: 55ee3f6ad1cace50 + en: ac86e691a0994600 + zh: 99d2409389c9aa12 /deepseek-ai-dsh-host-webserver/known-limitations-and-deferred-work/dev-note: en: 245b35764295ba1e zh: a15b132b111bfef0 diff --git a/packages/host/webserver/README.md b/packages/host/webserver/README.md index 59313177e2..5288a1039b 100644 --- a/packages/host/webserver/README.md +++ b/packages/host/webserver/README.md @@ -58,13 +58,21 @@ Set `compression: 'gzip'` to wrap eligible socket-backed responses without chang ### Registering routes +WebServer events use the emitting WebServer as their Cordis subject. Ordinary listeners receive events only from the same `webServer` isolation; `{ global: true }` explicitly opts out. This applies to request handling, page injection, and entry-URL collection. Custom emitters must pass their WebServer instance as the subject too. + `register(route)` adds a named `exact` or `prefix` HTTP route, `registerUpgrade(route)` adds an upgrade route for an exact pathname, and both return a disposer that removes the registration. A duplicate path within either table throws — route patterns are a composition-level contract, so a collision is a misconfiguration. HTTP matching is exact over the whole table, then longest prefix, then the fallback; upgrades match exactly and unmatched connections are closed. -A named route may give `resource(request, peer?)` instead of `handler`: a function from a Fetch `Request` to a `Response`. Over HTTP only `GET` and `HEAD` reach it — any other method is answered 405 with `Allow: GET, HEAD` and its body is never read — and the request carries no Peer, the client's headers, and a URL that is the request target resolved against a placeholder origin; the client's authority stays only in the `host` header. The response is written back with backpressure and the gzip decision a handler's response gets; `HEAD` sends no body, and a client disconnect aborts `request.signal` and cancels the body. `readResource(request, peer)` returns the response the same URL would receive over HTTP, computed by the resource for `peer` (a `HEAD` read returns no body): it follows the HTTP match order, answers 404 when the path belongs to a handler or reaches a fallback that is unclaimed or a handler, answers 405 for a method other than `GET` or `HEAD`, and checks no cookie, Host, or Origin, so its caller admits the reader first. +A named route may give `resource(request, peer?)` instead of `handler`: a function from a Fetch `Request` to a `Response`. After admission, only `GET` and `HEAD` reach it; other methods receive 405 with `Allow: GET, HEAD`, without reading the body. The resource receives the admitted Peer, if any, and the client headers; its URL resolves the request target against a placeholder origin, leaving the client authority in `host`. Responses use backpressure and the same gzip handling as handlers; `HEAD` sends no body, and disconnect aborts `request.signal` and cancels the body. `readResource(request, peer)` dispatches in process with its explicitly admitted Peer: it checks no cookie, Host, or Origin, but a resolved `deny` returns 403. It follows HTTP match order, returns 404 for handlers or an unclaimed fallback, and 405 for non-GET/HEAD reads; HEAD reads return no body. + +HTTP requests pass through `webserver/request(request, response, next)` before route lookup. A listener owns the response or awaits `next()`; the request-error handler contains middleware failures. After matching, HTTP and upgrade routes resolve `auth`, either a fixed policy or a synchronous selector over request facts. `required` is the default and requires a live Peer; `anonymous` removes the credential requirement; `deny` returns 403 without dispatch. For other policies, synchronous `webserver/authorize(request, policy)` takes the first decision. Without a decision, `anonymous` allows and `required` returns 503. HTTP and upgrade admission refusals carry `Cache-Control: no-store`. Connection supplies source checks and ordered credential verification; its source checks also apply to anonymous routes. HTTP handlers receive `(req, res, peer?)`, upgrades `(req, socket, head, peer?)`, and resources keep their Peer parameter. In-process reads do not emit this event. + +Admitted upgrades pass through `webserver/upgrade(req, socket, head, peer, next)` before their registered protocol handler. The waterfall carries the already selected Peer, or `undefined` for anonymous admission; denied requests never enter it. A listener handles the Socket itself or awaits `next()` to delegate. WebServer awaits synchronous or asynchronous protocol handlers and contains rejected middleware or handlers by logging and destroying that Socket. Provider-specific Socket limits and credential cleanup belong to listeners, not to WebServer or Gateway. + +`webserver/entry-url(baseUrl, entries)` synchronously collects complete entry URLs for a supplied server base URL. Listeners append `{ label, url, open }` entries. WebApp emits it after readiness. WebApp owns ordered printing and the first eligible browser handoff. This event neither authenticates requests nor changes the listener or advertised-address configuration. ### The fallback seat -`registerFallback(handler)` or `registerFallback({ resource })` claims the one responder for every request no named route matches. A second registration throws; while no fallback is registered the server answers 404. In the shipped Web composition the [SPA dist server](../frontend-static/README.md) owns the seat and calls `renderIndex` on every index response it renders. +`registerFallback(handler)` or an object containing `handler` or `resource` and optional `auth` claims the one responder for unmatched requests. A bare handler still defaults to `required` admission. A second registration throws; an unclaimed seat returns 404. In the shipped Web composition the [SPA dist server](../frontend-static/README.md) owns the seat, selects authenticated index access and anonymous assets, and calls `renderIndex` for index responses. Index startup inputs are two layers, computed for the Peer the page speaks for. `collectIndexInjections(peer)` gathers a fresh injection table — one `webserver/index-inject` emit per call, passing `peer` to each subscriber, which pushes its current rows — and `renderIndex(html, peer)` renders those rows into the index.html body before applying the raw `tapIndex(transform)` transforms in registration order. A `script-preload` row renders an advisory classic-script preload link. Static deployments carry the same rows in their boot payload. `applyIndexTaps(html)` applies only the raw transforms; it is the escape hatch for markup no row expresses. @@ -82,7 +90,7 @@ A listen failure (for example EADDRINUSE) rejects plugin initialization with the ### Design concept -The package is a plain route registry whose only harness vocabulary is the Peer an index render speaks for: `WebServer` extends Cordis `Service` and holds three route tables plus the fallback slot, the raw index-tap list, and the `webserver/index-inject` event the index renderer gathers rows through. Index rendering composes two layers per response: `renderIndex` renders the fresh injection table, including advisory `script-preload` rows, into the body, then applies the raw taps in registration order; `applyIndexTaps` runs the taps alone. The upgrade handler owns the protocol handshake and connection contents; the webserver only delivers the raw socket and request. `host`, `port`, and `protocol` getters and `getOrigin()` expose composition-time facts other plugins adapt to (for example the directory-picker chooser), and an explicit `tls: null` normalizes to an unset listener, so `protocol` has a single source. +`WebServer` extends Cordis `Service` and owns matching, route admission, response delivery, and index rendering. Connection supplies source/credential decisions through an event rather than a WebServer dependency on a concrete authentication implementation. Index rendering gathers fresh `webserver/index-inject` rows, renders them, then applies raw taps. The upgrade handler owns protocol negotiation and connection contents after admission. Listener getters and `getOrigin()` expose configuration-derived transport facts; explicit `tls: null` means an HTTP listener. ### Matching and lifecycle @@ -129,7 +137,7 @@ None; this package neither assembles nor sends a provider request. These limits define where the server is intentionally minimal. They are current package constraints, not a task backlog. - **No certificate lifecycle** — `tls` serves the PEM files present at activation: the carrier never provisions, renews, or watches them, and it applies Node's default TLS policy. Replacing a certificate takes a reload. -- **No server-wide authentication or origin policy** — route owners such as `dsh-client-connection` enforce their own request policy. Binding a non-loopback address still exposes unprotected routes and static assets to that network. +- **Credential and source policy need an authorization listener** — the carrier enforces route declarations but verifies no credentials itself. Without a decision, authenticated routes return 503 and anonymous routes remain reachable; an active Connection listener applies source checks to both. - **Socket options are fixed** — config selects the bind host and port, while backlog and other socket settings remain internal until a deployment needs them. diff --git a/packages/host/webserver/README.zh.md b/packages/host/webserver/README.zh.md index aa8cde6345..0fce2aac11 100644 --- a/packages/host/webserver/README.zh.md +++ b/packages/host/webserver/README.zh.md @@ -58,13 +58,21 @@ kind: "package-reference" ### 注册路由 +WebServer 事件以发起它的 WebServer 为 Cordis subject。普通监听器仅接收相同 `webServer` isolation 中的事件;`{ global: true }` 明确跳过此过滤。请求处理、页面注入和入口 URL 收集均遵循此规则。自定义发起者也必须把自己的 WebServer 实例作为 subject 传入。 + `register(route)` 添加具名的 `exact`/`prefix` HTTP route,`registerUpgrade(route)` 为精确 pathname 添加 upgrade route,两者返回的 disposer 都会移除注册。同一张表内的重复路径会抛错——route 模式是组合层约定,冲突即配置错误。HTTP 匹配先在整张表中匹配精确 route,再匹配最长前缀,最后交给回退;upgrade 只做精确匹配,未命中连接直接关闭。 -具名 route 可以用 `resource(request, peer?)` 代替 `handler`:一个把 Fetch `Request` 映射为 `Response` 的函数。经 HTTP 时只有 `GET` 与 `HEAD` 能到达它——其他方法得到带 `Allow: GET, HEAD` 的 405,请求 body 从不读取——请求不带 Peer,携带客户端的 header,URL 是把请求目标按一个占位 origin 解析得到的,客户端的 authority 只保留在 `host` 头里。响应按背压写回,gzip 的处理与 handler 的响应相同;`HEAD` 不发送 body,客户端断开会中止 `request.signal` 并取消 body。`readResource(request, peer)` 返回同一 URL 经 HTTP 会得到的响应,由 resource 按 `peer` 计算(`HEAD` 读取不返回 body):它遵循 HTTP 的匹配顺序;路径属于 handler、或落到未认领或 handler 形式的回退时返回 404;`GET`、`HEAD` 以外的方法返回 405;不检查 cookie、Host 或 Origin,因此调用方须先准入读者。 +具名路由可以使用 `resource(request, peer?)` 代替 `handler`,将 Fetch `Request` 映射为 `Response`。准入后仅 `GET` 与 `HEAD` 可到达 resource;其他方法返回带 `Allow: GET, HEAD` 的405,不读取正文。resource 接收准入 Peer(若有)与客户端请求头;URL 将请求目标按占位 origin 解析,客户端 authority 保留在 `host` 中。响应按背压及与 handler 相同的 gzip 规则发送;`HEAD` 不发送正文,断开会中止 `request.signal` 并取消正文。`readResource(request, peer)` 使用显式准入的 Peer 在进程内分发,不检查 Cookie、Host 或 Origin,但解析出的 `deny` 返回403。它遵循 HTTP 匹配顺序,对 handler 或未认领回退返回404,对非 GET/HEAD 读取返回405;HEAD 读取不返回正文。 + +HTTP 请求在路由查找前经过 `webserver/request(request, response, next)`。监听器拥有响应或等待 `next()`,请求错误处理器容纳中间件异常。匹配后,HTTP 与 upgrade 路由解析 `auth`,可为固定策略或读取请求事实的同步选择器。默认 `required` 要求存活 Peer;`anonymous` 免凭据;`deny` 不分发,直接返回403。其余策略通过同步 `webserver/authorize(request, policy)` 采用首个决策。无人决策时匿名放行,认证返回503。HTTP 与 upgrade 的准入拒绝响应均携带 `Cache-Control: no-store`。Connection 提供来源检查与有序凭据验证;来源检查同样适用于匿名路由。HTTP handler 接收 `(req, res, peer?)`,upgrade 接收 `(req, socket, head, peer?)`,resource 保留已有 Peer 参数。进程内读取不触发此事件。 + +已准入的 upgrade 在已注册协议 handler 前经过 `webserver/upgrade(req, socket, head, peer, next)`。waterfall 携带已选定的 Peer,匿名准入可为 `undefined`;被拒绝的请求不会进入。监听器自行处理 Socket,或等待 `next()` 委派。WebServer 等待同步或异步协议 handler,并在中间件或 handler 拒绝时记录日志、销毁该 Socket。Provider 专属 Socket 限制与凭据清理属于监听器,不属于 WebServer 或 Gateway。 + +`webserver/entry-url(baseUrl, entries)` 根据传入的服务器基地址同步收集完整入口 URL。监听器追加 `{ label, url, open }` 入口。WebApp 在就绪后触发该事件。WebApp 拥有按序打印与首个可自动打开入口的浏览器交接。该事件不认证请求,也不改变监听器或公告地址配置。 ### 回退席位 -`registerFallback(handler)` 或 `registerFallback({ resource })` 认领所有未被具名 route 命中的请求的唯一一个应答方。第二次注册会抛错;没有注册回退时服务器回答 404。在随附的 Web 组合中,[SPA dist 服务器](../frontend-static/README.zh.md)拥有该席位,并对其渲染的每个 index 响应调用 `renderIndex`。 +`registerFallback(handler)` 或含 `handler`/`resource` 及可选 `auth` 的对象认领未匹配请求的唯一应答方。裸 handler 同样默认采用 `required` 准入。第二次注册抛错,未认领席位返回404。随附 Web 组合由 [SPA dist 服务器](../frontend-static/README.zh.md)持有席位,选择 index 认证访问及静态资源匿名访问,并为 index 响应调用 `renderIndex`。 index 启动输入分两层,按页面所代表的 Peer 计算。`collectIndexInjections(peer)` 收集一张全新的注入表——每次调用发一次 `webserver/index-inject` 事件,把 `peer` 传给每个订阅方,订阅方推入其当前行——`renderIndex(html, peer)` 先把这些行渲染进 index.html 正文,再按注册顺序应用原始 `tapIndex(transform)` 转换。`script-preload` 行会渲染为 classic script 的提示性 preload 链接。静态部署会在启动 payload 中携带同一批行。`applyIndexTaps(html)` 只应用原始转换;它是任何行都无法表达的标记的逃生口。 @@ -82,7 +90,7 @@ index 启动输入分两层,按页面所代表的 Peer 计算。`collectIndexI ### 设计理念 -本包是一个普通路由注册表,唯一的 harness 词汇是 index 渲染所代表的 Peer:`WebServer` 继承 Cordis `Service`,持有三张路由表、回退 slot、原始 index 转换列表,以及 `webserver/index-inject` 事件,index 渲染器经其收集行。index 渲染每次响应组合两层:`renderIndex` 先把包含提示性 `script-preload` 行的全新注入表渲染进正文,再按注册顺序应用原始转换;`applyIndexTaps` 只运行转换。upgrade handler 拥有协议握手与连接内容;webserver 只交付原始 socket 与 request。`host`、`port`、`protocol` getter 与 `getOrigin()` 暴露其他插件据以自适应的组合期事实(例如 directory-picker 选择器),而显式的 `tls: null` 会归一为未设置监听,使 `protocol` 只有一个来源。 +`WebServer` 继承 Cordis `Service`,拥有匹配、路由准入、响应交付与 index 渲染。Connection 通过事件提供来源/凭据决策,WebServer 不依赖具体认证实现。index 渲染收集新的 `webserver/index-inject` 行,渲染后执行原始转换。upgrade handler 在准入后拥有协议协商与连接内容。监听器 getter 与 `getOrigin()` 暴露配置决定的传输事实;显式 `tls: null` 表示 HTTP 监听器。 ### 匹配与生命周期 @@ -129,7 +137,7 @@ index 启动输入分两层,按页面所代表的 Peer 计算。`collectIndexI 这些限制说明服务器在何处有意保持最小。它们是当前包约束,不是任务积压。 - **不管理证书生命周期**:`tls` 只提供激活时存在的 PEM 文件——载体从不申请、续期或监视它们,并采用 Node 默认的 TLS 策略。替换证书需要重新加载。 -- **不提供服务器级认证或来源策略**:`dsh-client-connection` 等 route owner 会实施自己的请求策略。绑定非回环地址仍会向该网络公开未受保护的 route 与静态资源。 +- **凭据与来源策略需要准入监听器**——载体执行路由声明,但不自行验证凭据。无人决策时,认证路由返回503,匿名路由仍可访问;活动 Connection 监听器对两者均执行来源检查。 - **Socket 选项固定不变**:配置只选择绑定宿主与端口;在具体部署产生需求前,backlog 和其他 socket 设置仍保持内部实现。 diff --git a/packages/host/webserver/src/index.ts b/packages/host/webserver/src/index.ts index 6d613e8a49..3ed162f3b4 100644 --- a/packages/host/webserver/src/index.ts +++ b/packages/host/webserver/src/index.ts @@ -7,6 +7,8 @@ * Route handlers retain direct response ownership; a route or the fallback may * instead give a resource, which maps a Fetch `Request` to a `Response` and * also answers in-process reads. + * WebServer events use the instance as their subject: ordinary listeners follow + * its webServer isolation, while explicitly global listeners receive every instance. */ import { readFile } from 'node:fs/promises' @@ -27,11 +29,55 @@ import { renderIndexInjections, type IndexInjection } from './injections.ts' export { renderIndexInjections } from './injections.ts' export type { IndexInjection, IndexInjectionPlacement } from './injections.ts' +/** One application entry URL contributed for startup printing or browser handoff. */ +export interface WebEntryUrl { + /** Output prefix, such as `dsh web`. */ + readonly label: string + /** Complete entry URL, including any credentials required by its provider. */ + readonly url: string + /** Whether this entry is eligible for the application's automatic browser handoff. */ + readonly open: boolean +} + declare module '@deepseek-ai/cordis' { interface Context { webServer: WebServer } interface Events { + /** + * Collect complete entry URLs for an advertised server address. + * @param baseUrl - advertised server base URL without provider credentials. + * @param entries - entries appended synchronously in listener order. + * @mode emit + */ + 'webserver/entry-url'(baseUrl: string, entries: WebEntryUrl[]): void + /** + * Admit a matched request synchronously; the first decision wins. + * @param request - headers, target, transport, and available cancellation state. + * @param policy - resolved route policy; deny never emits this event. + * @mode bail + */ + 'webserver/authorize'(request: WebAuthRequest, policy: WebAuthPolicy): WebAdmission | undefined + /** + * Handle an HTTP request before named-route and fallback dispatch. + * @param request - original incoming HTTP request. + * @param response - response owned by the listener or its delegated handler. + * @param next - dispatch to the next listener or the matching route. + * @mode waterfall + */ + 'webserver/request'(request: IncomingMessage, response: ServerResponse, next: () => Promise): Promise + /** + * Handle an admitted upgrade before its registered protocol handler. + * @param request - original upgrade request. + * @param socket - transport owned by the upgrade. + * @param head - bytes received after the HTTP headers. + * @param peer - authenticated identity, absent for anonymous admission. + * @param next - delegate to the next listener or protocol handler. + * @mode waterfall + */ + 'webserver/upgrade'( + request: IncomingMessage, socket: Duplex, head: Buffer, peer: PeerScope | undefined, next: () => Promise, + ): Promise /** * Collect the structured index injection table for the page `peer` speaks * for. Emitted on every index render and every worker boot-payload @@ -45,6 +91,25 @@ declare module '@deepseek-ai/cordis' { } } +/** A route permits anonymous access, requires a live Peer, or refuses all access. */ +export type WebAuthPolicy = 'anonymous' | 'required' | 'deny' + +/** Authentication inputs shared by socket-backed and synthetic requests. */ +export interface WebAuthRequest { + headers: Headers | Readonly> + method?: string | undefined + url: URL + transport: 'http' | 'upgrade' + signal?: AbortSignal | undefined + socket?: { readonly destroyed: boolean } | undefined +} + +/** Fixed route policy or a synchronous policy selector. */ +export type WebAuthenticationRule = WebAuthPolicy | ((request: WebAuthRequest) => WebAuthPolicy) + +/** First authorization decision; authenticated access requires a live Peer. */ +export type WebAdmission = { kind: 'allow'; peer?: PeerScope } | { kind: 'deny'; status: 401 | 403 | 503 } + /** Route match kind: 'exact' matches the pathname verbatim; 'prefix' p matches p and p/. */ export type WebRouteKind = 'exact' | 'prefix' @@ -54,12 +119,14 @@ export interface WebRoute { /** Absolute pathname, no trailing slash. */ path: string /** Owns the full response lifecycle (may hold the response open, e.g. SSE). */ - handler: (req: IncomingMessage, res: ServerResponse) => void | Promise + handler: (req: IncomingMessage, res: ServerResponse, peer?: PeerScope) => void | Promise + /** Defaults to required. Anonymous handlers may receive no Peer. */ + auth?: WebAuthenticationRule } /** - * Answers one GET or HEAD request with a Fetch response. An HTTP request - * arrives without a Peer and carries the client's headers; an in-process + * Answers one GET or HEAD request with a Fetch response and its admitted Peer. + * Anonymous HTTP admission may omit the Peer; an in-process * {@link WebServer.readResource} read passes the Peer its caller admitted. */ export type WebResource = (request: Request, peer?: PeerScope) => Promise @@ -71,14 +138,21 @@ export interface WebResourceRoute { path: string /** Answers HTTP GET and HEAD requests and in-process reads. */ resource: WebResource + /** Defaults to required; in-process reads still enforce deny. */ + auth?: WebAuthenticationRule } +/** The unmatched-request responder; omitted auth requires authentication. */ +export type WebFallback = Pick | Pick + /** One exact-path HTTP upgrade registration. */ export interface WebUpgradeRoute { /** Absolute pathname, no trailing slash. */ path: string /** Owns protocol negotiation and the upgraded socket after dispatch. */ - handler: (req: IncomingMessage, socket: Duplex, head: Buffer) => void | Promise + handler: (req: IncomingMessage, socket: Duplex, head: Buffer, peer?: PeerScope) => void | Promise + /** Defaults to required. Anonymous handlers may receive no Peer. */ + auth?: WebAuthenticationRule } /** @@ -352,7 +426,8 @@ async function writeResponse(res: ServerResponse, response: Response, head: bool * initialization, and the boot process reports the failed fiber. Route * registration order does not affect requests because configured named routes * must be distinct, and a request no named route matches is answered 404 - * until the fallback owner registers. + * until the fallback owner registers. HTTP and upgrade admission refusals + * carry `Cache-Control: no-store`. */ export class WebServer extends Service { static Config: z = z.object({ @@ -388,7 +463,7 @@ export class WebServer extends Service { */ private readonly tlsConnections = new Set() private readonly indexTaps: ((html: string) => string)[] = [] - private fallback: WebRoute['handler'] | Pick | undefined + private fallback: WebFallback | undefined private server!: Server private listenedPort: number | undefined private readonly gzip: NodeMiddleware | undefined @@ -471,14 +546,14 @@ export class WebServer extends Service { * composition). One owner only — a second registration throws, because two * fallbacks cannot compose. * @param fallback - a handler owning the full response lifecycle of - * unmatched requests, or `{ resource }` answering them. + * unmatched requests, or an object declaring `handler` or `resource` and auth. * @returns the disposer releasing the seat. */ - registerFallback(fallback: WebRoute['handler'] | Pick): () => void { + registerFallback(fallback: WebRoute['handler'] | WebFallback): () => void { if (this.fallback !== undefined) { throw new Error('webserver: fallback already registered') } - this.fallback = fallback + this.fallback = typeof fallback === 'function' ? { handler: fallback } : fallback return () => { this.fallback = undefined } } @@ -488,6 +563,7 @@ export class WebServer extends Service { * path picks the responder by the HTTP match order — exact, longest prefix, * then the fallback — and only a resource answers. This method checks no * cookie, Host, or Origin: the caller admits the reader before reading. + * A resolved deny policy returns 403 even for an explicitly admitted Peer. * @param request - the read; its URL path selects the responder. * @param peer - the Peer the read speaks for, passed to the resource. * @returns the resource's response, without a body for HEAD as over HTTP; @@ -501,8 +577,12 @@ export class WebServer extends Service { if (request.method !== 'GET' && request.method !== 'HEAD') { return new Response(null, { status: 405, headers: { allow: RESOURCE_METHODS } }) } - const responder = this.responderFor(new URL(request.url).pathname) - if (typeof responder !== 'object' || !('resource' in responder)) return new Response(null, { status: 404 }) + const url = new URL(request.url) + const responder = this.responderFor(url.pathname) + if (responder === undefined || !('resource' in responder)) return new Response(null, { status: 404 }) + if (this.authPolicy(responder.auth, { headers: request.headers, method: request.method, url, transport: 'http', signal: request.signal }) === 'deny') { + return new Response(null, { status: 403 }) + } const response = await responder.resource(request, peer) if (request.method === 'GET') return response await response.body?.cancel() @@ -536,9 +616,34 @@ export class WebServer extends Service { res.end() return } - if (typeof responder === 'function') await responder(req, res) - else if ('resource' in responder) await this.serveResource(req, res, target, responder.resource) - else await responder.handler(req, res) + const abort = new AbortController() + const cleanup = (): void => { + res.off('close', onClose) + res.off('finish', cleanup) + } + const onClose = (): void => { + abort.abort() + cleanup() + } + res.once('close', onClose) + res.once('finish', cleanup) + try { + const request: WebAuthRequest = { + headers: req.headers, method: req.method, url: target, transport: 'http', + signal: abort.signal, socket: req.socket, + } + const admission = this.authorize(request, responder.auth) + if (abort.signal.aborted || request.socket?.destroyed) return + if (admission.kind === 'deny') { + res.writeHead(admission.status, { 'Cache-Control': 'no-store' }) + res.end(admission.status === 401 ? 'unauthorized' : admission.status === 503 ? 'authentication unavailable' : 'forbidden') + return + } + if ('resource' in responder) await this.serveResource(req, res, target, responder.resource, abort.signal, admission.peer) + else await responder.handler(req, res, admission.peer) + } finally { + if (res.writableEnded || abort.signal.aborted) cleanup() + } } // Last-resort guard: handle() rejecting would otherwise be an unhandled // rejection killing the process on one malformed request (bad %-escape, @@ -546,7 +651,8 @@ export class WebServer extends Service { // never a process exit. const listener = (req: IncomingMessage, res: ServerResponse): void => { const next = (): void => { - void handle(req, res).catch((err: unknown) => { + const dispatch = async (): Promise => { await this.ctx.waterfall(this, 'webserver/request', req, res, () => handle(req, res)) } + void dispatch().catch((err: unknown) => { this.ctx.logger.warn(err instanceof Error ? err : new Error(String(err))) if (res.headersSent) { res.destroy() @@ -592,9 +698,11 @@ export class WebServer extends Service { this.upgradedSockets.delete(socket) }) let route: WebUpgradeRoute | undefined + let target: URL try { /* v8 ignore next -- node:http always sets url on server requests. */ - route = this.upgrades.get(new URL(req.url ?? '/', 'http://x').pathname) + target = new URL(req.url ?? '/', 'http://x') + route = this.upgrades.get(target.pathname) } catch (error) { this.ctx.logger.warn(error instanceof Error ? error : new Error(String(error))) socket.destroy() @@ -605,8 +713,26 @@ export class WebServer extends Service { return } this.upgradedSockets.add(socket) + const abort = new AbortController() + socket.once('close', () => { abort.abort() }) try { - Promise.resolve(route.handler(req, socket, head)).catch((error: unknown) => { + const admission = this.authorize({ + headers: req.headers, method: req.method, url: target, transport: 'upgrade', + signal: abort.signal, socket, + }, route.auth) + if (abort.signal.aborted || socket.destroyed) return + if (admission.kind === 'deny') { + const reason = { 401: 'Unauthorized', 403: 'Forbidden', 503: 'Service Unavailable' }[admission.status] + const body = reason.toLowerCase() + socket.end(`HTTP/1.1 ${String(admission.status)} ${reason}\r\nConnection: close\r\nCache-Control: no-store\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: ${String(Buffer.byteLength(body))}\r\n\r\n${body}`) + return + } + const dispatch = async (): Promise => { + await this.ctx.waterfall(this, 'webserver/upgrade', req, socket, head, admission.peer, async () => { + if (!socket.destroyed) await route.handler(req, socket, head, admission.peer) + }) + } + void dispatch().catch((error: unknown) => { this.ctx.logger.warn(error instanceof Error ? error : new Error(String(error))) socket.destroy() }) @@ -647,10 +773,26 @@ export class WebServer extends Service { * The responder for one request path, shared by HTTP requests and * {@link readResource}: the matched named route, otherwise the fallback. */ - private responderFor(pathname: string): WebRoute | WebResourceRoute | WebRoute['handler'] | Pick | undefined { + private responderFor(pathname: string): WebFallback | undefined { return this.match(pathname) ?? this.fallback } + private authPolicy(auth: WebAuthenticationRule | undefined, request: WebAuthRequest): WebAuthPolicy { + return typeof auth === 'function' ? auth(request) : auth ?? 'required' + } + + private authorize(request: WebAuthRequest, auth: WebAuthenticationRule | undefined): WebAdmission { + const policy = this.authPolicy(auth, request) + if (policy === 'deny') return { kind: 'deny', status: 403 } + const admission: WebAdmission = this.ctx.bail(this, 'webserver/authorize', request, policy) + ?? (policy === 'anonymous' ? { kind: 'allow' } : { kind: 'deny', status: 503 }) + if (admission.kind === 'allow') { + if (policy === 'required' && admission.peer === undefined) return { kind: 'deny', status: 503 } + if (admission.peer?.signal.aborted) return { kind: 'deny', status: 401 } + } + return admission + } + /** Longest-prefix-wins over the prefix table after an exact-table miss. */ private match(pathname: string): WebRoute | WebResourceRoute | undefined { const exact = this.exact.get(pathname) @@ -666,13 +808,15 @@ export class WebServer extends Service { /** * Answer one HTTP exchange from a resource. Only GET and HEAD reach it; * any other method receives 405 and its request body is never read. The - * request becomes a Fetch `Request` without a Peer whose URL is the request + * request becomes a Fetch `Request` whose URL is the request * target resolved against a placeholder origin, as the match reads it; the * client's authority stays only in the `host` header. The connection * closing before this method ends the response aborts the request signal * and cancels the response body. */ - private async serveResource(req: IncomingMessage, res: ServerResponse, target: URL, resource: WebResource): Promise { + private async serveResource( + req: IncomingMessage, res: ServerResponse, target: URL, resource: WebResource, signal: AbortSignal, peer?: PeerScope, + ): Promise { if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405, { allow: RESOURCE_METHODS }) res.end() @@ -682,24 +826,9 @@ export class WebServer extends Service { for (const [name, value] of Object.entries(req.headers)) { for (const item of typeof value === 'string' ? [value] : value ?? []) headers.append(name, item) } - const abort = new AbortController() - // An own flag, not `writableEnded`: the Web Worker tunnel marks an aborted - // response ended before it emits `close`. - let ended = false - const onClose = (): void => { - if (!ended) abort.abort() - } - res.on('close', onClose) - try { - const response = await resource(new Request(target, { method: req.method, headers, signal: abort.signal })) - await writeResponse(res, response, req.method === 'HEAD', abort.signal) - if (!abort.signal.aborted) { - ended = true - res.end() - } - } finally { - res.off('close', onClose) - } + const response = await resource(new Request(target, { method: req.method, headers, signal }), peer) + await writeResponse(res, response, req.method === 'HEAD', signal) + if (!signal.aborted) res.end() } /** @@ -724,7 +853,7 @@ export class WebServer extends Service { */ collectIndexInjections(peer: PeerScope): IndexInjection[] { const table: IndexInjection[] = [] - this.ctx.emit('webserver/index-inject', table, peer) + this.ctx.emit(this, 'webserver/index-inject', table, peer) return table } diff --git a/packages/host/webserver/tests/event-isolation.host.spec.ts b/packages/host/webserver/tests/event-isolation.host.spec.ts new file mode 100644 index 0000000000..5d7828d1fb --- /dev/null +++ b/packages/host/webserver/tests/event-isolation.host.spec.ts @@ -0,0 +1,88 @@ +/** WebServer request and page events follow each instance's service isolation. */ +import { once } from 'node:events' +import type { IncomingMessage, ServerResponse } from 'node:http' +import { connect } from 'node:net' +import { Context } from '@deepseek-ai/cordis' +import type { PeerScope } from '@deepseek-ai/dsh-typert-protocol' +import { expect, it, onTestFinished } from 'vitest' +import WebServer from '../src/index.ts' + +it('filters HTTP, upgrade, and index listeners while retaining explicitly global listeners', async () => { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + const isolated = ctx.isolate('webServer') + await ctx.plugin(WebServer, { host: '127.0.0.1', port: 0 }).await() + await isolated.plugin(WebServer, { host: '127.0.0.1', port: 0 }).await() + const servers = [ctx.webServer, isolated.webServer] + const calls: string[] = [] + ctx.on('webserver/request', async function (this: unknown, _req: IncomingMessage, _res: ServerResponse, next: () => Promise) { + expect(this).toBeInstanceOf(WebServer) + calls.push('global:request') + await next() + }, { global: true }) + ctx.on('webserver/authorize', () => { calls.push('global:authorize') }, { global: true }) + ctx.on('webserver/upgrade', async (_req, _socket, _head, _peer, next) => { + calls.push('global:upgrade') + await next() + }, { global: true }) + ctx.on('webserver/index-inject', (rows) => { + rows.push({ kind: 'global', name: 'globalEntry', value: true }) + }, { global: true }) + + for (const [scope, label] of [[ctx, 'main'], [isolated, 'isolated']] as const) { + scope.on('webserver/request', async (_req, _res, next) => { + calls.push(`${label}:request`) + await next() + }) + scope.on('webserver/authorize', () => { + calls.push(`${label}:authorize`) + return { kind: 'allow' } + }) + scope.on('webserver/upgrade', async (_req, _socket, _head, _peer, next) => { + calls.push(`${label}:upgrade`) + await next() + }) + scope.on('webserver/index-inject', (rows) => { + rows.push({ kind: 'global', name: label, value: true }) + }) + scope.effect(() => scope.webServer.register({ + kind: 'exact', path: '/probe', auth: 'anonymous', + handler(_req, res) { res.end(label) }, + })) + scope.effect(() => scope.webServer.registerUpgrade({ + path: '/socket', auth: 'anonymous', + handler(_req, socket) { + socket.end('HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: probe\r\n\r\n') + }, + })) + } + + for (const [index, label] of ['main', 'isolated'].entries()) { + const server = servers[index]! + calls.length = 0 + const response = await fetch(`${server.getOrigin()}/probe`) + expect(await response.text()).toBe(label) + expect(calls).toEqual(['global:request', `${label}:request`, 'global:authorize', `${label}:authorize`]) + + calls.length = 0 + const socket = connect(server.port!, '127.0.0.1') + const closed = new Promise((resolve) => { socket.once('close', () => { resolve() }) }) + onTestFinished(async () => { socket.destroy(); await closed }) + await once(socket, 'connect') + let output = '' + socket.setEncoding('utf8').on('data', (data: string) => { output += data }) + socket.write('GET /socket HTTP/1.1\r\nHost: localhost\r\nConnection: Upgrade\r\nUpgrade: probe\r\n\r\n') + await closed + expect(output).toContain('101 Switching Protocols') + expect(calls).toEqual(['global:authorize', `${label}:authorize`, 'global:upgrade', `${label}:upgrade`]) + + const peer: PeerScope = { + id: label as PeerScope['id'], ctx, principal: { kind: 'owner' }, interactions: 'none', + signal: new AbortController().signal, async dispose() {}, + } + expect(server.collectIndexInjections(peer)).toEqual([ + { kind: 'global', name: 'globalEntry', value: true }, + { kind: 'global', name: label, value: true }, + ]) + } +}) diff --git a/packages/host/webserver/tests/webserver.spec.ts b/packages/host/webserver/tests/webserver.spec.ts index 783b0c86dc..0ebf4abec8 100644 --- a/packages/host/webserver/tests/webserver.spec.ts +++ b/packages/host/webserver/tests/webserver.spec.ts @@ -15,7 +15,7 @@ import { Agent, request as httpsRequest } from 'node:https' import { connect, createServer as createTcpServer, type AddressInfo } from 'node:net' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' -import type { Duplex } from 'node:stream' +import { Duplex } from 'node:stream' import { pathToFileURL } from 'node:url' import { afterEach, describe, expect, it, vi } from 'vitest' import { Context, FiberState } from '@deepseek-ai/cordis' @@ -24,6 +24,7 @@ import Include from '@deepseek-ai/cordis-plugin-include' import type { PeerScope } from '@deepseek-ai/dsh-typert-protocol' import HttpServer, { bindUrlHost, isLoopbackHost, normalizeBindAddress, renderIndexInjections, type TlsConfig, type WebResource, type WebRoute, + type WebAuthRequest, } from '../src/index.ts' import { materializeTlsFixture, type TlsFixture } from './tls-fixture.ts' @@ -247,6 +248,279 @@ function tlsUpgrade(port: number | undefined, path: string, ca: string): Promise } describe('real Loader composition', () => { + it.each([401, 403, 503] as const)('marks HTTP and upgrade admission refusals %s as non-cacheable', async (status) => { + const ctx = await loadComposition() + const handler = vi.fn() + ctx.webServer.register({ kind: 'exact', path: '/private', handler }) + ctx.webServer.registerUpgrade({ path: '/private', handler }) + ctx.on('webserver/authorize', () => ({ kind: 'deny', status })) + + const response = await request(ctx.webServer.port, '/private') + expect(response.status).toBe(status) + expect(response.headers.get('cache-control')).toBe('no-store') + const upgraded = await rawExchange(ctx.webServer.port, + 'GET /private HTTP/1.1\r\nHost: localhost\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n') + expect(upgraded).toMatch(new RegExp(`^HTTP/1.1 ${String(status)} `, 'u')) + expect(upgraded).toContain('\r\nCache-Control: no-store\r\n') + expect(handler).not.toHaveBeenCalled() + }) + + it('authenticates matched HTTP routes once and forwards the admitted Peer', async () => { + const ctx = await loadComposition() + const server = ctx.webServer + const abort = new AbortController() + const peer: PeerScope = { + id: 'route-auth' as PeerScope['id'], ctx, principal: { kind: 'owner' }, signal: abort.signal, + interactions: 'none', async dispose() { abort.abort() }, + } + const reached: (PeerScope | undefined)[] = [] + const handler: WebRoute['handler'] = (_req, res, admitted) => { reached.push(admitted); res.end('allowed') } + server.register({ kind: 'exact', path: '/private', handler }) + server.register({ kind: 'prefix', path: '/public', auth: 'anonymous', handler }) + server.register({ kind: 'exact', path: '/public/secret', auth: 'deny', handler }) + expect(await request(server.port, '/private')).toMatchObject({ status: 503, body: 'authentication unavailable' }) + expect((await request(server.port, '/public')).status).toBe(200) + expect(reached).toEqual([undefined]) + const seen: WebAuthRequest[] = [] + const listener = ctx.plugin({ apply(scope: Context) { + scope.on('webserver/authorize', (incoming, policy) => { + seen.push(incoming) + if (policy === 'anonymous') return { kind: 'allow' } + if (incoming.headers instanceof Headers || incoming.headers.authorization !== 'Bearer valid') return { kind: 'deny', status: 401 } + return { kind: 'allow', peer } + }) + } }) + await listener.await() + const later = vi.fn(() => ({ kind: 'deny' as const, status: 403 as const })) + const removeLater = ctx.on('webserver/authorize', later) + expect((await request(server.port, '/missing')).status).toBe(404) + expect(await request(server.port, '/public/secret')).toMatchObject({ status: 403, body: 'forbidden' }) + expect(seen).toHaveLength(0) + expect((await request(server.port, '/private')).status).toBe(401) + expect((await request(server.port, '/private', { headers: { authorization: 'Bearer valid' } })).status).toBe(200) + expect(reached.at(-1)).toBe(peer) + expect(seen.at(-1)).toMatchObject({ method: 'GET', transport: 'http' }) + expect(seen.at(-1)?.url.pathname).toBe('/private') + expect(seen.at(-1)?.socket?.destroyed).toBe(false) + expect(later).not.toHaveBeenCalled() + await peer.dispose() + expect((await request(server.port, '/private', { headers: { authorization: 'Bearer valid' } })).status).toBe(401) + await listener.dispose() + removeLater() + expect(await request(server.port, '/private')).toMatchObject({ status: 503, body: 'authentication unavailable' }) + }) + + it('resolves selectors for resources and fallback while trusting explicit in-process Peers', async () => { + const ctx = await loadComposition() + const server = ctx.webServer + const peer: PeerScope = { + id: 'resource-auth' as PeerScope['id'], ctx, principal: { kind: 'owner' }, signal: new AbortController().signal, + interactions: 'none', async dispose() {}, + } + const resource = vi.fn(async (_request: Request, admitted?: PeerScope) => { + expect(admitted).toBe(peer) + return new Response('resource') + }) + server.register({ kind: 'exact', path: '/resource', resource, auth: incoming => incoming.url.searchParams.has('deny') ? 'deny' : 'required' }) + const authorize = vi.fn(() => ({ kind: 'allow' as const, peer })) + ctx.on('webserver/authorize', authorize) + expect(await request(server.port, '/resource', { method: 'HEAD' })).toMatchObject({ status: 200, body: '' }) + expect(authorize).toHaveBeenCalledTimes(1) + expect(resource).toHaveBeenCalledTimes(1) + const direct = await server.readResource(new Request('http://reader.invalid/resource', { headers: { authorization: 'invalid' } }), peer) + expect(await direct.text()).toBe('resource') + expect(authorize).toHaveBeenCalledTimes(1) + expect((await server.readResource(new Request('http://reader.invalid/resource?deny'), peer)).status).toBe(403) + expect((await request(server.port, '/resource?deny', { method: 'HEAD' })).status).toBe(403) + expect(resource).toHaveBeenCalledTimes(2) + expect(authorize).toHaveBeenCalledTimes(1) + const release = server.registerFallback({ auth: incoming => incoming.url.pathname === '/blocked' ? 'deny' : 'required', resource }) + expect((await request(server.port, '/fallback')).body).toBe('resource') + expect((await request(server.port, '/blocked')).status).toBe(403) + release() + }) + + it('requires admission for bare fallback handlers and rejects an allow without a required Peer', async () => { + const ctx = await loadComposition() + const reached = vi.fn((_req, res) => { res.end('unexpected') }) + ctx.webServer.registerFallback(reached) + expect((await request(ctx.webServer.port, '/fallback')).status).toBe(503) + const stop = ctx.on('webserver/authorize', () => ({ kind: 'allow' })) + expect((await request(ctx.webServer.port, '/fallback')).status).toBe(503) + stop() + ctx.on('webserver/authorize', () => { throw new Error('authorization failed') }) + expect((await request(ctx.webServer.port, '/fallback')).status).toBe(400) + expect(reached).not.toHaveBeenCalled() + }) + + it('authorizes upgrade routes before dispatch and forwards their Peer', async () => { + const ctx = await loadComposition() + const server = ctx.webServer + const peer: PeerScope = { + id: 'upgrade-auth' as PeerScope['id'], ctx, principal: { kind: 'owner' }, signal: new AbortController().signal, + interactions: 'none', async dispose() {}, + } + const stages: string[] = [] + const removeMiddleware = ctx.on('webserver/upgrade', async (_request, _socket, _head, incomingPeer, next) => { + expect(incomingPeer).toBe(peer) + stages.push('before') + await next() + stages.push('after') + }) + let admitted: PeerScope | undefined + server.registerUpgrade({ path: '/private', handler(_req, socket, _head, incoming) { + admitted = incoming + stages.push('handler') + socket.end('HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n') + } }) + server.registerUpgrade({ path: '/denied', auth: 'deny', handler() { throw new Error('must not dispatch') } }) + const exchange = (path: string) => rawExchange(server.port, `GET ${path} HTTP/1.1\r\nHost: localhost\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n`) + expect(await exchange('/private')).toContain('503 Service Unavailable') + expect(await exchange('/denied')).toContain('403 Forbidden') + expect(await exchange('/missing')).toBe('') + const reject = ctx.on('webserver/authorize', () => ({ kind: 'deny', status: 401 })) + expect(await exchange('/private')).toContain('401 Unauthorized') + expect(stages).toEqual([]) + reject() + let incoming: WebAuthRequest | undefined + const allow = ctx.on('webserver/authorize', (request) => { incoming = request; return { kind: 'allow', peer } }) + expect(await exchange('/private?x=1')).toContain('101 Switching Protocols') + expect(admitted).toBe(peer) + expect(stages).toEqual(['before', 'handler', 'after']) + removeMiddleware() + const veto = ctx.on('webserver/upgrade', async (_req, socket) => { socket.end('HTTP/1.1 409 Conflict\r\n\r\n') }) + expect(await exchange('/private?x=1')).toContain('409 Conflict') + expect(stages).toEqual(['before', 'handler', 'after']) + veto() + expect(incoming?.url.search).toBe('?x=1') + expect(incoming?.transport).toBe('upgrade') + await vi.waitFor(() => { expect(incoming?.signal?.aborted).toBe(true) }) + allow() + ctx.on('webserver/authorize', () => { throw new Error('upgrade authorization failed') }) + expect(await exchange('/private')).toBe('') + }) + + it('propagates HTTP cancellation to authorization and the resource without reauthenticating', async () => { + const ctx = await loadComposition() + const cancelled = Promise.withResolvers() + let admissionSignal: AbortSignal | undefined + let resourceSignal: AbortSignal | undefined + ctx.on('webserver/authorize', (incoming) => { admissionSignal = incoming.signal; return { kind: 'allow' } }) + ctx.webServer.register({ kind: 'exact', path: '/stream', auth: 'anonymous', resource: async (incoming) => { + resourceSignal = incoming.signal + return new Response(new ReadableStream({ + start(controller) { controller.enqueue(new TextEncoder().encode('ready')) }, + cancel() { cancelled.resolve(undefined) }, + })) + } }) + const abort = new AbortController() + const response = await fetch(`${ctx.webServer.getOrigin()}/stream`, { signal: abort.signal }) + await response.body!.getReader().read() + expect(admissionSignal?.aborted).toBe(false) + abort.abort() + await cancelled.promise + expect(admissionSignal?.aborted).toBe(true) + expect(resourceSignal?.aborted).toBe(true) + }) + + it('contains selector failures and never dispatches a synchronously closed request', async () => { + const ctx = await loadComposition() + const server = ctx.webServer + const handler = vi.fn((_req, res) => { res.end('unexpected') }) + server.register({ kind: 'exact', path: '/throws', auth() { throw new Error('selector failed') }, handler }) + expect((await request(server.port, '/throws')).status).toBe(400) + server.register({ kind: 'exact', path: '/closed', auth: 'anonymous', handler }) + let closeRequest = (): void => {} + ctx.on('webserver/request', async (req, _res, next) => { closeRequest = () => { req.socket.destroy() }; await next() }) + ctx.on('webserver/authorize', () => { closeRequest(); return { kind: 'allow' } }) + expect(await rawExchange(server.port, 'GET /closed HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n')).toBe('') + expect(handler).not.toHaveBeenCalled() + }) + + it('dispatches anonymous upgrades without a provider and contains selector and handler failures', async () => { + const ctx = await loadComposition() + const server = ctx.webServer + const exchange = (path: string) => rawExchange(server.port, `GET ${path} HTTP/1.1\r\nHost: localhost\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n`) + server.registerUpgrade({ path: '/public', auth: 'anonymous', handler(_req, socket, _head, peer) { + expect(peer).toBeUndefined() + socket.end('HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n') + } }) + expect(await exchange('/public')).toContain('101 Switching Protocols') + server.registerUpgrade({ path: '/selector', auth() { throw new Error('upgrade selector failed') }, handler() {} }) + server.registerUpgrade({ path: '/sync', auth: 'anonymous', handler() { throw new Error('sync upgrade failed') } }) + server.registerUpgrade({ path: '/async', auth: 'anonymous', async handler() { throw new Error('async upgrade failed') } }) + for (const path of ['/selector', '/sync', '/async']) expect(await exchange(path)).toBe('') + expect(await exchange('http://[')).toBe('') + }) + + it('does not dispatch upgrades destroyed during synchronous admission', async () => { + const ctx = await loadComposition() + const handler = vi.fn() + ctx.webServer.registerUpgrade({ path: '/closed', auth: 'anonymous', handler }) + const socket = new Duplex({ read() {}, write(_chunk, _encoding, callback) { callback() } }) + const closed = once(socket, 'close') + ctx.on('webserver/authorize', (incoming) => { + expect(incoming.socket).toBe(socket) + socket.destroy() + return { kind: 'allow' } + }) + const server = Reflect.get(ctx.webServer, 'server') as { emit(event: 'upgrade', req: object, socket: Duplex, head: Buffer): boolean } + server.emit('upgrade', { url: '/closed', method: 'GET', headers: {} }, socket, Buffer.alloc(0)) + await closed + expect(handler).not.toHaveBeenCalled() + }) + + it('runs HTTP middleware before dispatch and delegates only through next', async () => { + const ctx = await loadComposition() + const server = ctx.webServer + const calls: string[] = [] + server.register({ auth: 'anonymous', kind: 'exact', path: '/resource', resource: async () => { + calls.push('resource') + return new Response('resource') + } }) + const middleware = ctx.plugin({ apply(scope: Context) { + scope.on('webserver/request', async (req, res, next) => { + calls.push('before') + if (req.url === '/exchange') { + res.writeHead(303, { location: './', 'set-cookie': 'fixture=valid' }) + res.end() + return + } + await next() + calls.push('after') + }) + } }) + await middleware.await() + expect((await request(server.port, '/resource')).body).toBe('resource') + expect(calls).toEqual(['before', 'resource', 'after']) + calls.length = 0 + const response = await fetch(`http://127.0.0.1:${String(server.port)}/exchange`, { redirect: 'manual' }) + expect(response.status).toBe(303) + expect(response.headers.get('set-cookie')).toBe('fixture=valid') + await response.text() + expect(calls).toEqual(['before']) + calls.length = 0 + const peer = { principal: { kind: 'owner' } } as PeerScope + expect(await (await server.readResource(new Request('http://reader.invalid/resource'), peer)).text()).toBe('resource') + expect(calls).toEqual(['resource']) + await middleware.dispose() + calls.length = 0 + expect((await request(server.port, '/resource')).body).toBe('resource') + expect(calls).toEqual(['resource']) + }) + + it('contains synchronous middleware failures before reaching the route', async () => { + const ctx = await loadComposition() + let reached = false + ctx.webServer.register({ auth: 'anonymous', kind: 'exact', path: '/guarded', handler(_req, res) { + reached = true + res.end('unexpected') + } }) + ctx.on('webserver/request', () => { throw new Error('middleware failed') }) + expect((await request(ctx.webServer.port, '/guarded')).status).toBe(400) + expect(reached).toBe(false) + }) + it('accepts one concrete IP literal, keeping an IPv6 zone for listen', () => { for (const host of ['127.0.0.1', '10.1.2.3', '0.1.2.3', '::1', 'fd00::1', '::ffff:10.1.2.3', '::ffff:0.1.2.3', '0:0:0:0:0:0:0:1', 'fe80::1%lo', '::0.0.0.1', '::0.0.0.1%lo', '::127.0.0.1']) { expect(HttpServer.Config({ host, port: 0 }).host).toBe(host) @@ -346,7 +620,7 @@ describe('real Loader composition', () => { const loaded = await loadComposition(0, true) const server = loaded.webServer const body = 'compressible response '.repeat(8) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/text', handler: (_req, res) => { @@ -357,7 +631,7 @@ describe('real Loader composition', () => { res.end(body) }, }) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/stream', handler: (_req, res) => { @@ -366,7 +640,7 @@ describe('real Loader composition', () => { res.end(body.slice(40)) }, }) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/small', handler: (_req, res) => { @@ -374,7 +648,7 @@ describe('real Loader composition', () => { res.end('small') }, }) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/events', handler: (_req, res) => { @@ -382,7 +656,7 @@ describe('real Loader composition', () => { res.end(body) }, }) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/archive', handler: (_req, res) => { @@ -390,7 +664,7 @@ describe('real Loader composition', () => { res.end(body) }, }) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/range', handler: (_req, res) => { @@ -423,7 +697,7 @@ describe('real Loader composition', () => { .headers.get('content-encoding')).toBeNull() // A resource response passes through the same gzip decision as a handler's. - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/resource-text', resource: () => Promise.resolve(new Response(body, { headers: { 'content-type': 'text/plain; charset=utf-8' } })), @@ -442,7 +716,7 @@ describe('real Loader composition', () => { process.on('warning', onWarning) try { const chunk = new TextEncoder().encode('compressible chunk '.repeat(64 * 1024 / 16)) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/resource-large', resource: () => Promise.resolve(new Response(new ReadableStream({ @@ -480,9 +754,9 @@ describe('real Loader composition', () => { // Routing precedence: exact beats prefix, longest prefix wins, a prefix // route answers its own path, and routes own their method handling // (POST reaches a registered prefix; 405 is fallback-only semantics). - server.register({ kind: 'exact', path: '/probe', handler: (_req, res) => { res.writeHead(200); res.end('EXACT') } }) - server.register({ kind: 'prefix', path: '/api', handler: (_req, res) => { res.writeHead(200); res.end('API') } }) - server.register({ kind: 'prefix', path: '/api/deep', handler: (_req, res) => { res.writeHead(200); res.end('DEEP') } }) + server.register({ auth: 'anonymous', kind: 'exact', path: '/probe', handler: (_req, res) => { res.writeHead(200); res.end('EXACT') } }) + server.register({ auth: 'anonymous', kind: 'prefix', path: '/api', handler: (_req, res) => { res.writeHead(200); res.end('API') } }) + server.register({ auth: 'anonymous', kind: 'prefix', path: '/api/deep', handler: (_req, res) => { res.writeHead(200); res.end('DEEP') } }) expect(await request(port, '/probe')).toMatchObject({ status: 200, body: 'EXACT' }) expect(await request(port, '/api/anything')).toMatchObject({ status: 200, body: 'API' }) expect(await request(port, '/api/deep/leaf')).toMatchObject({ status: 200, body: 'DEEP' }) @@ -495,13 +769,13 @@ describe('real Loader composition', () => { expect((await request(port, '/no/such/route')).status).toBe(404) const untap = server.tapIndex(html => html.replace('', '')) expect(server.applyIndexTaps('')).toContain('__T__') - const releaseFallback = server.registerFallback((req, res) => { + const releaseFallback = server.registerFallback({ auth: 'anonymous', handler: (req, res) => { // Decode like a real static server would — a malformed %-escape throws // here, probing the webserver's per-request error containment. decodeURIComponent(new URL(req.url ?? '/', 'http://x').pathname) res.writeHead(200, { 'content-type': 'text/html' }) res.end(server.applyIndexTaps('shell')) - }) + } }) expect(() => server.registerFallback(() => {})).toThrow(/fallback already registered/) expect((await request(port, '/no/such/route')).body).toContain('__T__') untap() @@ -515,13 +789,13 @@ describe('real Loader composition', () => { // Duplicate (kind, path) is a misconfiguration and throws; the disposer // restores registrability (register/disposer symmetry). - expect(() => server.register({ kind: 'exact', path: '/probe', handler: () => {} })) + expect(() => server.register({ auth: 'anonymous', kind: 'exact', path: '/probe', handler: () => {} })) .toThrow(/duplicate exact route/) - const disposeOnce = server.register({ kind: 'exact', path: '/once', handler: (_req, res) => { res.writeHead(200); res.end('ONCE') } }) + const disposeOnce = server.register({ auth: 'anonymous', kind: 'exact', path: '/once', handler: (_req, res) => { res.writeHead(200); res.end('ONCE') } }) expect(await request(port, '/once')).toMatchObject({ status: 200, body: 'ONCE' }) disposeOnce() expect((await request(port, '/once')).body).toContain('shell') // back to the fallback owner - expect(() => server.register({ kind: 'exact', path: '/once', handler: () => {} })).not.toThrow() + expect(() => server.register({ auth: 'anonymous', kind: 'exact', path: '/once', handler: () => {} })).not.toThrow() // Releasing the seat restores the unclaimed 404 and registrability. releaseFallback() @@ -532,22 +806,22 @@ describe('real Loader composition', () => { // become registrable again after disposal. The accepted socket stays open // so the teardown assertion also covers upgraded-connection ownership. let upgradedServerClosed = false - const disposeUpgrade = server.registerUpgrade({ + const disposeUpgrade = server.registerUpgrade({ auth: 'anonymous', path: '/events', handler: (_req, socket) => { socket.once('close', () => { upgradedServerClosed = true }) socket.write('HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n') }, }) - expect(() => server.registerUpgrade({ path: '/events', handler: () => {} })) + expect(() => server.registerUpgrade({ auth: 'anonymous', path: '/events', handler: () => {} })) .toThrow(/duplicate upgrade route/) const upgraded = await upgrade(port, '/events?stream=mux') disposeUpgrade() - expect(() => server.registerUpgrade({ path: '/events', handler: () => {} })).not.toThrow() + expect(() => server.registerUpgrade({ auth: 'anonymous', path: '/events', handler: () => {} })).not.toThrow() // The webserver contains raw-socket errors even before an upgrade handler // has installed its protocol implementation. - server.registerUpgrade({ + server.registerUpgrade({ auth: 'anonymous', path: '/upgrade-error', handler: async (_req, socket) => { await Promise.resolve() @@ -592,7 +866,7 @@ describe('real Loader composition', () => { cookie: string | null peer: PeerScope | undefined } | undefined - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/resource', resource: (request, peer) => { @@ -627,7 +901,7 @@ describe('real Loader composition', () => { // The status and headers arrive before the first body chunk exists. const firstChunk = Promise.withResolvers() - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/held', resource: () => Promise.resolve(new Response(new ReadableStream({ @@ -646,7 +920,7 @@ describe('real Loader composition', () => { // A streamed body reaches the client chunk by chunk: the first chunk is // readable while the second is still withheld. const second = Promise.withResolvers() - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/stream', resource: () => Promise.resolve(new Response(new ReadableStream({ @@ -668,7 +942,7 @@ describe('real Loader composition', () => { // HEAD writes the status and headers, sends no body, and cancels the body. const headCancelled = Promise.withResolvers() - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/head', resource: () => Promise.resolve(new Response(new ReadableStream({ @@ -681,7 +955,7 @@ describe('real Loader composition', () => { // A client leaving mid-body aborts the request signal and cancels the body. const cancelled = Promise.withResolvers() let endlessSignal: AbortSignal | undefined - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/endless', resource: (request) => { @@ -701,7 +975,7 @@ describe('real Loader composition', () => { // Only GET and HEAD reach a resource; another method is 405 and its body is never read. let posted = false - server.register({ kind: 'exact', path: '/posted', resource: () => { posted = true; return Promise.resolve(new Response('POSTED')) } }) + server.register({ auth: 'anonymous', kind: 'exact', path: '/posted', resource: () => { posted = true; return Promise.resolve(new Response('POSTED')) } }) const refused = await request(port, '/posted', { method: 'POST', body: 'payload' }) expect(refused).toMatchObject({ status: 405, body: '' }) expect(refused.headers.get('allow')).toBe('GET, HEAD') @@ -714,7 +988,7 @@ describe('real Loader composition', () => { expect(seen?.url).toBe('http://x/resource?q=2') expect(await rawExchange(port, 'GET /resource?q=3 HTTP/1.1\r\nHost: bad host\r\nConnection: close\r\n\r\n')).toMatch(/^HTTP\/1\.1 201/) expect([seen?.url, seen?.host]).toEqual(['http://x/resource?q=3', 'bad host']) - server.register({ kind: 'exact', path: '/throws', resource: () => Promise.reject(new Error('resource failure')) }) + server.register({ auth: 'anonymous', kind: 'exact', path: '/throws', resource: () => Promise.reject(new Error('resource failure')) }) expect((await request(port, '/throws')).status).toBe(400) expect((await request(port, '/resource')).status).toBe(201) }) @@ -727,7 +1001,7 @@ describe('real Loader composition', () => { const server = loaded.webServer const cancelled = Promise.withResolvers() const firstChunk = Promise.withResolvers() - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/tunnel', resource: () => Promise.resolve(new Response(new ReadableStream({ @@ -775,10 +1049,10 @@ describe('real Loader composition', () => { res.writeHead(200) res.end(label) } - server.register({ kind: 'prefix', path: '/assets', resource: resource('assets') }) - server.register({ kind: 'prefix', path: '/assets/deep', resource: resource('deep') }) - server.register({ kind: 'exact', path: '/assets/special', handler: handler('SPECIAL') }) - server.register({ kind: 'prefix', path: '/api', handler: handler('API') }) + server.register({ auth: 'anonymous', kind: 'prefix', path: '/assets', resource: resource('assets') }) + server.register({ auth: 'anonymous', kind: 'prefix', path: '/assets/deep', resource: resource('deep') }) + server.register({ auth: 'anonymous', kind: 'exact', path: '/assets/special', handler: handler('SPECIAL') }) + server.register({ auth: 'anonymous', kind: 'prefix', path: '/api', handler: handler('API') }) // Exact, then longest prefix: the same responder HTTP picks answers the // read, and the read passes its Peer to the resource. @@ -802,11 +1076,11 @@ describe('real Loader composition', () => { // The fallback seat answers a read only while it holds a resource. expect((await read('/elsewhere')).status).toBe(404) - const releaseHandler = server.registerFallback(handler('FALLBACK')) + const releaseHandler = server.registerFallback({ auth: 'anonymous', handler: handler('FALLBACK') }) expect((await read('/elsewhere')).status).toBe(404) expect((await request(port, '/elsewhere')).body).toBe('FALLBACK') releaseHandler() - server.registerFallback({ resource: resource('fallback') }) + server.registerFallback({ auth: 'anonymous', resource: resource('fallback') }) const fallback = await read('/elsewhere') expect(await fallback.text()).toBe('fallback:/elsewhere') expect(readersOf.at(-1)).toBe(peer) @@ -819,7 +1093,7 @@ describe('real Loader composition', () => { expect(readersOf).toHaveLength(calls) // A throwing resource rejects the read; over HTTP the same failure is 400. - server.register({ kind: 'exact', path: '/throws', resource: () => Promise.reject(new Error('resource failure')) }) + server.register({ auth: 'anonymous', kind: 'exact', path: '/throws', resource: () => Promise.reject(new Error('resource failure')) }) await expect(read('/throws')).rejects.toThrow('resource failure') expect((await request(port, '/throws')).status).toBe(400) }) @@ -897,7 +1171,7 @@ describe('real Loader composition', () => { const server = loaded.webServer expect(server.protocol).toBe('https:') expect(server.getOrigin()).toBe(`https://127.0.0.1:${String(server.port)}`) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/tls', handler: (_req, res) => { @@ -923,7 +1197,7 @@ describe('real Loader composition', () => { const server = loaded.webServer expect(server.protocol).toBe('http:') expect(server.getOrigin()).toBe(`http://127.0.0.1:${String(server.port)}`) - server.register({ kind: 'exact', path: '/plain', handler: (_req, res) => { res.writeHead(200); res.end('PLAIN') } }) + server.register({ auth: 'anonymous', kind: 'exact', path: '/plain', handler: (_req, res) => { res.writeHead(200); res.end('PLAIN') } }) expect(await request(server.port, '/plain')).toMatchObject({ status: 200, body: 'PLAIN' }) await expect(tlsRequest(server.port, '/plain')).rejects.toThrow() }) @@ -994,14 +1268,14 @@ describe('real Loader composition', () => { const loaded = await loadComposition(0, false, '127.0.0.1', { certFile: fixture.certFile, keyFile: fixture.keyFile }) const server = loaded.webServer let upgradeClosed = false - server.registerUpgrade({ + server.registerUpgrade({ auth: 'anonymous', path: '/events', handler: (_req, socket) => { socket.once('close', () => { upgradeClosed = true }) socket.write('HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n') }, }) - server.register({ kind: 'exact', path: '/probe', handler: (_req, res) => { res.writeHead(200); res.end('EXACT') } }) + server.register({ auth: 'anonymous', kind: 'exact', path: '/probe', handler: (_req, res) => { res.writeHead(200); res.end('EXACT') } }) const clients = new Map>() const clientErrors: Error[] = [] diff --git a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md index da06785281..533a1f5765 100644 --- a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md +++ b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md @@ -286,6 +286,8 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo | Package | Config | Description | |---|---|---| +| `@deepseek-ai/dsh-host-authentication-desktop` | yes | Desktop private-channel authentication provider | +| `@deepseek-ai/dsh-host-authentication-token` | yes | Default token authentication provider and HTTP cookie exchange | | `@deepseek-ai/dsh-host-directory-picker-auto` | no | Adaptive chooser of the directory-picker seam: resolves the host situation at boot and mounts the native or browse backend for the DeepSeek Harness web GUI host | | `@deepseek-ai/dsh-host-directory-picker-browse` | yes | In-app browsing backend of the directory-picker seam (listing/creation primitives over the host filesystem) | | `@deepseek-ai/dsh-host-directory-picker-native` | no | Native-OS-chooser backend of the directory-picker seam for the DeepSeek Harness web GUI host | diff --git a/packages/session-query/session-log-export/tests/archive.host.spec.ts b/packages/session-query/session-log-export/tests/archive.host.spec.ts index 61791185b3..46ea244bae 100644 --- a/packages/session-query/session-log-export/tests/archive.host.spec.ts +++ b/packages/session-query/session-log-export/tests/archive.host.spec.ts @@ -16,8 +16,7 @@ import type { SessionEvent, SessionHeader, SessionId, ToolResultMessage, UserMes import type { SessionLineageNode } from '@deepseek-ai/dsh-session-query' import { SessionPersistenceNotFoundError } from '@deepseek-ai/dsh-session-persistence' import type { SessionAccess, SessionHandle } from '@deepseek-ai/dsh-session-persistence' -import { HostConnectionService } from '@deepseek-ai/dsh-client-connection' -import type { BrowserAuth } from '@deepseek-ai/dsh-client-connection/src/browser-auth.ts' +import { ConnectionAuthentication, HostConnectionService } from '@deepseek-ai/dsh-client-connection' import * as SessionLogExport from '../src/index.ts' declare module '@deepseek-ai/dsh-llm' { @@ -171,7 +170,8 @@ async function buildApi( } as never) } if (services.sessions !== undefined) ctx.provide('sessions', services.sessions as never) - const connection = new HostConnectionService(ctx, [], {} as BrowserAuth) + new ConnectionAuthentication(ctx) + const connection = new HostConnectionService(ctx, []) const fiber = ctx.plugin(SessionLogExport, { ...services.compressionLevel === undefined ? {} diff --git a/packages/session-query/session-log-export/tests/markdown-route.host.spec.ts b/packages/session-query/session-log-export/tests/markdown-route.host.spec.ts index 86f15828fe..29e21fae67 100644 --- a/packages/session-query/session-log-export/tests/markdown-route.host.spec.ts +++ b/packages/session-query/session-log-export/tests/markdown-route.host.spec.ts @@ -1,6 +1,5 @@ import { Context } from '@deepseek-ai/cordis' -import { HostConnectionService } from '@deepseek-ai/dsh-client-connection' -import type { BrowserAuth } from '@deepseek-ai/dsh-client-connection/src/browser-auth.ts' +import { ConnectionAuthentication, HostConnectionService } from '@deepseek-ai/dsh-client-connection' import type { MessageId } from '@deepseek-ai/dsh-llm' import type { SessionEvent, SessionHeader, SessionId, SessionSeq } from '@deepseek-ai/dsh-session' import { SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' @@ -89,7 +88,8 @@ async function mounted( ctx.provide('commands', { register: () => () => {} } as never) if (sessionQuery !== undefined) ctx.provide('sessionQuery', sessionQuery as never) if (persistence !== undefined) ctx.provide('sessionPersistence', persistence as SessionPersistence) - const connection = new HostConnectionService(ctx, [], {} as BrowserAuth) + new ConnectionAuthentication(ctx) + const connection = new HostConnectionService(ctx, []) const fiber = ctx.plugin({ inject: [...inject], apply }) await fiber return { diff --git a/packages/session-query/session-log-export/tests/route.host.spec.ts b/packages/session-query/session-log-export/tests/route.host.spec.ts index 5d793aec0e..eeff55888d 100644 --- a/packages/session-query/session-log-export/tests/route.host.spec.ts +++ b/packages/session-query/session-log-export/tests/route.host.spec.ts @@ -1,6 +1,5 @@ import { Context } from '@deepseek-ai/cordis' -import { HostConnectionService } from '@deepseek-ai/dsh-client-connection' -import type { BrowserAuth } from '@deepseek-ai/dsh-client-connection/src/browser-auth.ts' +import { ConnectionAuthentication, HostConnectionService } from '@deepseek-ai/dsh-client-connection' import { SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' import type { SessionHeader, SessionId } from '@deepseek-ai/dsh-session' import type { SessionHandle } from '@deepseek-ai/dsh-session-persistence' @@ -52,7 +51,8 @@ async function mounted(withServices: boolean): Promise<{ readImage: async () => { throw new Error('fixture has no images') }, } as never) } - const connection = new HostConnectionService(ctx, [], {} as BrowserAuth) + new ConnectionAuthentication(ctx) + const connection = new HostConnectionService(ctx, []) const fiber = ctx.plugin({ inject: [...inject], apply }) await fiber return { connection, dispose: () => fiber.dispose() } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9a21a45066..0d91895e89 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -755,6 +755,9 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../packages/util/brand + '@deepseek-ai/dsh-client-connection': + specifier: workspace:* + version: link:../../packages/client/connection '@deepseek-ai/dsh-client-product-analytics': specifier: workspace:* version: link:../../packages/client/product-analytics @@ -785,6 +788,12 @@ importers: '@deepseek-ai/dsh-home-paths': specifier: workspace:* version: link:../../packages/util/home-paths + '@deepseek-ai/dsh-host-authentication-desktop': + specifier: workspace:* + version: link:../../packages/host/authentication-desktop + '@deepseek-ai/dsh-host-webserver': + specifier: workspace:* + version: link:../../packages/host/webserver '@deepseek-ai/dsh-official-bundles': specifier: workspace:* version: link:../../packages/util/official-bundles @@ -881,6 +890,9 @@ importers: '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* version: link:../../packages/credentials/deepseek-account + '@deepseek-ai/dsh-host-authentication-desktop': + specifier: workspace:* + version: link:../../packages/host/authentication-desktop '@deepseek-ai/dsh-host-webserver': specifier: workspace:* version: link:../../packages/host/webserver @@ -900,6 +912,12 @@ importers: specifier: 3.1.1 version: 3.1.1 devDependencies: + '@deepseek-ai/dsh-api-gateway': + specifier: workspace:* + version: link:../../packages/api/gateway + '@deepseek-ai/dsh-api-remote-access': + specifier: workspace:* + version: link:../../packages/api/remote-access '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../packages/util/brand @@ -918,9 +936,18 @@ importers: '@deepseek-ai/dsh-session-persistence': specifier: workspace:* version: link:../../packages/session/session-persistence + '@deepseek-ai/dsh-typert-registry': + specifier: workspace:* + version: link:../../packages/typert/registry '@deepseek-ai/dsh-util-workspace-path': specifier: workspace:* version: link:../../packages/util/workspace-path + '@types/ws': + specifier: ^8.18.1 + version: 8.18.1 + ws: + specifier: ^8.21.3 + version: 8.21.3 apps/desktop-publisher: dependencies: @@ -3253,6 +3280,9 @@ importers: '@deepseek-ai/dsh-harness-dev-context': specifier: workspace:* version: link:../../context/harness-dev-context + '@deepseek-ai/dsh-host-authentication-token': + specifier: workspace:* + version: link:../../host/authentication-token '@deepseek-ai/dsh-host-directory-picker-auto': specifier: workspace:* version: link:../../host/directory-picker-auto @@ -3494,9 +3524,6 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand - '@deepseek-ai/dsh-credentials': - specifier: workspace:* - version: link:../../credentials/credentials '@deepseek-ai/schemastery': specifier: link:../../../vendor/schemastery version: link:../../../vendor/schemastery @@ -3510,6 +3537,12 @@ importers: '@deepseek-ai/dsh-attachment': specifier: workspace:* version: link:../../attachment/attachment + '@deepseek-ai/dsh-credentials': + specifier: workspace:* + version: link:../../credentials/credentials + '@deepseek-ai/dsh-host-authentication-token': + specifier: workspace:* + version: link:../../host/authentication-token '@deepseek-ai/dsh-host-webserver': specifier: workspace:* version: link:../../host/webserver @@ -8472,6 +8505,9 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand + '@deepseek-ai/dsh-client-connection': + specifier: workspace:* + version: link:../../client/connection '@deepseek-ai/dsh-credentials': specifier: workspace:* version: link:../credentials @@ -13357,6 +13393,52 @@ importers: specifier: workspace:* version: link:../../core/tools + packages/host/authentication-desktop: + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-client-connection': + specifier: workspace:* + version: link:../../client/connection + '@deepseek-ai/dsh-typert-protocol': + specifier: workspace:* + version: link:../../typert/protocol + + packages/host/authentication-token: + dependencies: + '@deepseek-ai/dsh-credentials': + specifier: workspace:* + version: link:../../credentials/credentials + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/cordis-plugin-include': + specifier: workspace:~ + version: link:../../../vendor/include + '@deepseek-ai/cordis-plugin-loader': + specifier: workspace:~ + version: link:../../../vendor/loader + '@deepseek-ai/dsh-client-connection': + specifier: workspace:* + version: link:../../client/connection + '@deepseek-ai/dsh-credentials-local': + specifier: workspace:* + version: link:../../credentials/credentials-local + '@deepseek-ai/dsh-host-frontend-static': + specifier: workspace:* + version: link:../frontend-static + '@deepseek-ai/dsh-host-webserver': + specifier: workspace:* + version: link:../webserver + '@deepseek-ai/dsh-typert-protocol': + specifier: workspace:* + version: link:../../typert/protocol + packages/host/directory-picker: devDependencies: '@deepseek-ai/cordis': @@ -13450,6 +13532,9 @@ importers: '@deepseek-ai/dsh-credentials-local': specifier: workspace:* version: link:../../credentials/credentials-local + '@deepseek-ai/dsh-host-authentication-token': + specifier: workspace:* + version: link:../authentication-token '@deepseek-ai/dsh-host-webserver': specifier: workspace:* version: link:../webserver @@ -13478,6 +13563,9 @@ importers: '@deepseek-ai/dsh-host-webserver': specifier: workspace:* version: link:../webserver + '@deepseek-ai/dsh-typert-protocol': + specifier: workspace:* + version: link:../../typert/protocol packages/host/plugin-inventory: dependencies: diff --git a/scripts/cordis-walk.ts b/scripts/cordis-walk.ts index 3a38f0ca29..80aeed6f34 100644 --- a/scripts/cordis-walk.ts +++ b/scripts/cordis-walk.ts @@ -72,7 +72,8 @@ export function contextKeyMap(body: ts.ModuleBlock, sf: ts.SourceFile): Map { expect(events).toEqual(['second/changed']) }) - it('reads string-literal and identifier member names from an Events merge', () => { + it('reads string-literal and identifier service and event names', () => { const sf = ts.createSourceFile('x.ts', [ "declare module '@deepseek-ai/cordis' {", ' interface Events {', @@ -196,6 +196,8 @@ describe('cordis-walk scan reach', () => { ' }', ' interface Context {', ' thing: ThingService', + " 'connection.authentication': AuthenticationService", + ' "connection.other": OtherService', ' }', '}', '', @@ -206,6 +208,10 @@ describe('cordis-walk scan reach', () => { : null if (!body) throw new Error('fixture did not parse to a module block') expect(eventNameList(body, sf)).toEqual(['scope/list', 'plain']) - expect([...contextKeyMap(body, sf)]).toEqual([['thing', 'ThingService']]) + expect([...contextKeyMap(body, sf)]).toEqual([ + ['thing', 'ThingService'], + ['connection.authentication', 'AuthenticationService'], + ['connection.other', 'OtherService'], + ]) }) }) diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 5c3da61024..90526d7a80 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -59,6 +59,7 @@ export const SERVICE_PAGE: Record = { productTelemetry: 'product-telemetry.md', productAnalytics: 'product-telemetry.md', connection: 'web-server.md', + 'connection.authentication': 'web-server.md', pluginManager: 'boot.md', actionCards: 'boot.md', pluginRecommendations: 'boot.md', @@ -313,6 +314,8 @@ export const EVENT_WALK_EXEMPTIONS: Record = { * appear on more than one page. */ export const LINK_MAP: Readonly> = { + AuthenticationProvider: '../../packages/client/connection/README.md#browser-authentication-and-request-trust', + PeerId: 'typert.md', Principal: 'typert.md', PrincipalMap: 'typert.md', RemoteAccessResource: 'typert.md', @@ -947,6 +950,12 @@ export const LINK_MAP: Readonly> = { PermissionCatalog: 'permission-presets.md', PresetOption: 'permission-presets.md', PresetSpec: 'permission-presets.md', + WebEntryUrl: 'web-server.md', + WebAdmission: 'web-server.md', + WebAuthPolicy: 'web-server.md', + WebAuthRequest: 'web-server.md', + WebAuthenticationRule: 'web-server.md', + WebFallback: 'web-server.md', WebRoute: 'web-server.md', WebResourceRoute: 'web-server.md', IndexInjection: 'web-server.md', @@ -1008,6 +1017,7 @@ export const FOUNDATION_TYPE_NAMES: ReadonlySet = new Set([ 'Plugin', 'AbortSignal', 'Headers', + 'URL', 'AsyncIterable', 'Context', 'Error', @@ -1028,6 +1038,8 @@ export const FOUNDATION_TYPE_NAMES: ReadonlySet = new Set([ 'ReadonlySet', 'Request', 'Response', + 'Buffer', + 'Duplex', 'IncomingMessage', 'ServerResponse', 'ReturnType', @@ -1043,18 +1055,14 @@ export const TYPE_LINK_EXEMPTIONS: Readonly> = { RecommendationDetails: 'packages/experimental/plugin-recommendations/README.md', ProductEvent: 'Desktop event fields are owned by packages/client/product-analytics/README.md and src/events.ts', ConnectionFetchHandler: 'shared Fetch dispatch is owned by packages/client/connection/src/rpc.ts', - ConnectionRequestRejection: 'transport rejection status is owned by packages/client/connection/src/rpc.ts', ConnectionTrustRequest: 'transport authentication input is owned by packages/client/connection/src/rpc.ts', PeerAdmission: 'Peer admission outcome is owned by packages/client/connection/src/rpc.ts', - ConnectionAdmission: 'physical socket admission and release are owned by packages/client/connection/src/rpc.ts', PeerScope: 'Peer scope contract is owned by packages/typert/protocol/src/types.ts', RemoteAccessPolicy: 'access policy contract is owned by packages/api/remote-access/README.md', RemoteAccessRequest: 'Gateway decision requests are owned by packages/api/remote-access/README.md', RemoteAccessDecision: 'Gateway decisions are owned by packages/api/remote-access/README.md', RemoteAccessFrame: 'access snapshot frames are owned by packages/api/remote-access/README.md', RemoteAccessBaseline: 'access snapshot frames are owned by packages/api/remote-access/README.md', - ConnectionIndexRequest: 'frontend authentication request is owned by packages/client/connection/src/rpc.ts', - ConnectionIndexResponse: 'frontend authentication response is owned by packages/client/connection/src/rpc.ts', Profile: 'resolved profile layers are owned by packages/boot/app-boot/README.md', PatchOptions: 'Include patch entries are owned by vendor/include (vendored upstream)', McpResourceProvider: 'scoped resource provider is owned by packages/mcp/mcp-resources/README.md', diff --git a/scripts/gen-doc-graphs.spec.ts b/scripts/gen-doc-graphs.spec.ts index 3274c79f12..9315e03b92 100644 --- a/scripts/gen-doc-graphs.spec.ts +++ b/scripts/gen-doc-graphs.spec.ts @@ -27,7 +27,15 @@ const FIXTURE: Record = { }, include: ['vendor/**/*.ts', 'packages/**/*.ts'], }), - 'vendor/cordis/src/context.ts': 'export class Context { private brand!: void }\n', + 'vendor/cordis/src/context.ts': [ + 'export class Context {', + ' private brand!: void', + ' bail(...args: unknown[]): void {}', + ' on(...args: unknown[]): void {}', + ' once(...args: unknown[]): void {}', + '}', + '', + ].join('\n'), 'vendor/cordis/src/events.ts': [ 'export class EventsService {', ' dispatch(type: string, args: unknown[]): unknown[] { return [type, args] }', @@ -63,6 +71,28 @@ const FIXTURE: Record = { 'packages/fix/pkgc/src/helper.ts': "function scriptFire(args: [string]): void { void gEvents.dispatch('emit', args) }\n", 'packages/fix/pkgc/src/caller.ts': "scriptFire(['pkgc/script-event'])\n", + 'packages/fix/bailtypes/src/receiver.ts': [ + "import { Context } from '../../../../vendor/cordis/src/context.ts'", + 'export declare const application: Context', + "export declare const event: 'bail/union-a' | 'bail/union-b'", + '', + ].join('\n'), + 'packages/fix/bailcalls/src/index.ts': [ + "import { application as receiver, event } from '../../bailtypes/src/receiver.ts'", + "receiver.bail('bail/direct')", + "receiver.bail({}, 'bail/scoped')", + 'receiver.bail(event)', + "receiver.on('bail/direct', () => {})", + "receiver.once('bail/scoped', () => {})", + 'declare const widened: string', + 'receiver.bail(widened)', + 'const ctx = { bail(...args: unknown[]): void {} }', + "ctx.bail('bail/unrelated')", + '// An untyped receiver cannot establish event API ownership.', + 'declare const untyped: any', + "untyped.bail('bail/untyped')", + '', + ].join('\n'), } const root = mkdtempSync(join(tmpdir(), 'gen-doc-graphs-')) @@ -99,6 +129,34 @@ describe('event relation call-site indexing', () => { }) }) +describe('type-aware bail dispatch', () => { + function collectBailRelations() { + return new EventRelationCollector(project, sources.filter(source => source.pkg === 'bailcalls')).collect() + } + + it.each(['bail/direct', 'bail/scoped', 'bail/union-a', 'bail/union-b'])( + 'records %s from an imported Context receiver as a bail dispatcher', + (event) => { + expect(collectBailRelations().get(event)?.dispatchers).toEqual(new Map([ + ['bailcalls', new Set(['bail'])], + ])) + }, + ) + + it('keeps on and once registrations as listeners', () => { + const relations = collectBailRelations() + expect(relations.get('bail/direct')?.listeners).toEqual(new Set(['bailcalls'])) + expect(relations.get('bail/scoped')?.listeners).toEqual(new Set(['bailcalls'])) + expect(relations.get('bail/union-a')?.listeners.size).toBe(0) + }) + + it('excludes unrelated and untyped receivers and widened event names', () => { + expect([...collectBailRelations().keys()].sort()).toEqual([ + 'bail/direct', 'bail/scoped', 'bail/union-a', 'bail/union-b', + ]) + }) +}) + describe('memoized filesystem probes', () => { function countingSystem(): { system: ts.System; calls: string[] } { const calls: string[] = [] diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 01d33a95e9..7078d12753 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -192,7 +192,16 @@ const SERVICE_ROLES: ServiceRole[] = [ title: 'Authenticated browser transport', mode: 'core', consumers: ['api-gateway', 'host-frontend-static'], - note: 'Owns browser authentication and shared HTTP request dispatch; API adapters register endpoints and streams.', + note: 'Applies source policy and shared HTTP request dispatch; credential verification belongs to ConnectionAuthentication, and API adapters register endpoints and streams.', + }, + { + key: 'connection.authentication', + pkg: 'client-connection', + title: 'Connection authentication provider registry', + mode: 'seam', + implementations: ['host-authentication-token', 'host-authentication-desktop'], + consumers: ['client-connection'], + note: 'Tries scope-owned credential verifiers in registration order and returns the first live Peer; transport source policy and business authorization stay with their consumers.', }, { key: 'forge', @@ -1178,7 +1187,7 @@ type CallSiteIndex = Map> = { + 'packages/host/authentication-desktop': { category: 'optional', reason: 'Mounted by the private Desktop Host with its parent-process credential, outside default Web profiles.' }, 'packages/core/agent-tool-presentation': { category: 'optional', reason: 'Deprecated selector retained for existing executor configurations.' }, 'packages/browser-use/browser-use': { category: 'optional', reason: 'Service definition used by explicitly selected browser providers.' }, 'packages/computer-use/computer-use': { category: 'optional', reason: 'Service definition used by explicitly selected computer providers.' }, diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index 2a19069258..6a626d8973 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -69,6 +69,8 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/experimental/voice-input-bundle': { kind: 'none', reason: 'Composes dictation and preparation plugins without adding any model-facing contribution.' }, 'packages/telemetry/otel': { kind: 'none', reason: 'The service delivers caller-selected records without changing model context.' }, 'packages/host/product-telemetry-otel': { kind: 'none', reason: 'The plugin exports explicit analytics records without contributing model context.' }, + 'packages/host/authentication-token': { kind: 'none', reason: 'Launch-token exchange and Cookie verification authenticate HTTP callers without contributing model input.' }, + 'packages/host/authentication-desktop': { kind: 'none', reason: 'Private Desktop credential verification authenticates HTTP callers without contributing model input.' }, 'packages/api/terminal-controller': { kind: 'indirect', reason: 'Working-directory recovery owns directory context; user terminal screens never enter model requests.' }, 'packages/client/ui-sidebar-terminal': { kind: 'none', reason: 'The browser renders user terminal screens without exposing them to the model.' }, 'packages/ssh/ssh-helper-runtime': { kind: 'none', reason: 'The private executable carrier registers no model-facing content; its providers and consumers own operation results.' }, diff --git a/tsconfig.base.json b/tsconfig.base.json index d14d434d5c..f7e5269ec6 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -251,6 +251,10 @@ "@deepseek-ai/dsh-host-open-in-app/shared": ["./packages/host/open-in-app/src/shared.ts"], "@deepseek-ai/dsh-host-webserver": ["./packages/host/webserver/src"], "@deepseek-ai/dsh-host-frontend-static": ["./packages/host/frontend-static/src"], + "@deepseek-ai/dsh-host-authentication-desktop": ["./packages/host/authentication-desktop/src/index.ts"], + "@deepseek-ai/dsh-host-authentication-desktop/src/*": ["./packages/host/authentication-desktop/src/*"], + "@deepseek-ai/dsh-host-authentication-token": ["./packages/host/authentication-token/src/index.ts"], + "@deepseek-ai/dsh-host-authentication-token/src/*": ["./packages/host/authentication-token/src/*"], "@deepseek-ai/dsh-plugin-manager": ["./packages/boot/plugin-manager/src"], "@deepseek-ai/dsh-plugin-manager/diagnostic": ["./packages/boot/plugin-manager/src/diagnostic.ts"], "@deepseek-ai/dsh-plugin-manager/types": ["./packages/boot/plugin-manager/src/types.ts"], diff --git a/tsconfig.host.json b/tsconfig.host.json index d77b87c35e..faa4315244 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -597,6 +597,8 @@ { "path": "./packages/host/directory-picker-browse" }, { "path": "./packages/host/directory-picker-native" }, { "path": "./packages/host/frontend-static" }, + { "path": "./packages/host/authentication-token" }, + { "path": "./packages/host/authentication-desktop" }, { "path": "./packages/host/open-in-app" }, { "path": "./packages/host/plugin-inventory" }, { "path": "./packages/boot/plugin-manager" }, From 695f640063cf3d348da278e65be05e0a40b4a6e9 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:11:54 +0800 Subject: [PATCH 321/404] Merge pull request #8133 from deepseek-harness/discuss-client-iframe refactor(client): add client module js realm (with module manifest and style operation) --- ...7-23-client-plugin-loading-model.i18n.yaml | 16 +- .../2026-07-23-client-plugin-loading-model.md | 10 +- ...26-07-23-client-plugin-loading-model.zh.md | 10 +- ...ient-shells-and-dynamic-packages.i18n.yaml | 4 +- ...8-15-client-shells-and-dynamic-packages.md | 6 +- ...5-client-shells-and-dynamic-packages.zh.md | 6 +- ...026-11-05-client-module-metadata.i18n.yaml | 19 + .../2026-11-05-client-module-metadata.md | 33 ++ .../2026-11-05-client-module-metadata.zh.md | 33 ++ apps/web/package.json | 3 + apps/web/tests/assembled-boot.ts | 3 + apps/web/tests/built-boot.expected.e2e.ts | 4 +- apps/web/tests/client-plugin-live.e2e.ts | 6 + .../tests/default-product-isolation.e2e.ts | 25 +- .../plugins/fixture-live-client/client.js | 13 +- apps/web/tests/navigation-panes.e2e.ts | 25 +- apps/web/tests/preview-boot.e2e.ts | 3 +- apps/web/tests/shell-command-details.e2e.ts | 4 +- .../web/tests/source-static-modules.client.ts | 41 ++ apps/web/tests/terminal-command-browser.ts | 8 +- apps/web/tests/window-drag-coverage.e2e.ts | 2 +- apps/web/vite.config.ts | 7 +- docs/config-catalog.md | 2 + docs/config-catalog.zh.md | 2 + docs/module-graph.md | 4 + docs/module-graph.zh.md | 4 + docs/subsystems/web-client.i18n.yaml | 4 +- docs/subsystems/web-client.md | 2 + docs/subsystems/web-client.zh.md | 2 + .../client-module-metadata/guide.i18n.yaml | 16 + .../client-module-metadata/guide.md | 29 ++ .../client-module-metadata/guide.zh.md | 29 ++ packages/client/AGENTS.md | 2 +- packages/client/modules/README.i18n.yaml | 21 +- packages/client/modules/README.md | 13 +- packages/client/modules/README.zh.md | 12 +- packages/client/modules/package.json | 3 +- packages/client/modules/src/client/entries.ts | 8 +- .../modules/src/client/entry-lifecycle.ts | 11 - packages/client/modules/src/client/index.ts | 2 +- .../client/modules/src/client/main-realm.ts | 46 ++ .../client/modules/src/client/manifest.ts | 84 ++-- packages/client/modules/src/client/system.ts | 217 +++++---- .../tests/document-module.client.spec.ts | 248 ++++++++++ .../modules/tests/entries.client.spec.ts | 225 +++++++-- .../modules/tests/loader.client.spec.ts | 213 ++++++--- .../modules/tests/main-realm.client.spec.ts | 91 ++++ .../modules/tests/node-half.client.spec.ts | 10 +- packages/client/modules/tsconfig.json | 1 + .../script-realm-iframe/README.i18n.yaml | 37 ++ packages/client/script-realm-iframe/README.md | 58 +++ .../client/script-realm-iframe/README.zh.md | 58 +++ .../client/script-realm-iframe/locale/de.json | 5 + .../client/script-realm-iframe/locale/en.json | 5 + .../client/script-realm-iframe/locale/es.json | 5 + .../client/script-realm-iframe/locale/fr.json | 5 + .../client/script-realm-iframe/locale/ja.json | 5 + .../client/script-realm-iframe/locale/pt.json | 5 + .../client/script-realm-iframe/locale/ru.json | 5 + .../client/script-realm-iframe/locale/zh.json | 5 + .../client/script-realm-iframe/package.json | 56 +++ .../script-realm-iframe/src/client/iframe.ts | 169 +++++++ .../script-realm-iframe/src/client/index.ts | 16 + .../client/script-realm-iframe/src/index.ts | 4 + .../tests/execution.client.spec.ts | 204 ++++++++ .../tests/realm.client.spec.ts | 33 ++ .../client/script-realm-iframe/tsconfig.json | 18 + .../script-realm-iframe/tsdown.config.ts | 3 + packages/client/script-realm/README.i18n.yaml | 37 ++ packages/client/script-realm/README.md | 58 +++ packages/client/script-realm/README.zh.md | 58 +++ packages/client/script-realm/locale/de.json | 5 + packages/client/script-realm/locale/en.json | 5 + packages/client/script-realm/locale/es.json | 5 + packages/client/script-realm/locale/fr.json | 5 + packages/client/script-realm/locale/ja.json | 5 + packages/client/script-realm/locale/pt.json | 5 + packages/client/script-realm/locale/ru.json | 5 + packages/client/script-realm/locale/zh.json | 5 + packages/client/script-realm/package.json | 55 +++ .../client/script-realm/src/client/index.ts | 80 ++++ .../client/script-realm/src/client/types.ts | 48 ++ packages/client/script-realm/src/index.ts | 2 + .../script-realm/tests/realm.client.spec.ts | 80 ++++ packages/client/script-realm/tsconfig.json | 18 + packages/client/script-realm/tsdown.config.ts | 3 + packages/client/tsdown.client.ts | 351 +++++++++++--- packages/client/ui-dockkit/README.i18n.yaml | 4 +- packages/client/ui-dockkit/README.md | 2 +- packages/client/ui-dockkit/README.zh.md | 2 +- .../ui-dockkit/src/components/TabLayout.tsx | 3 +- .../ui-dockkit/src/components/TabPanel.tsx | 2 +- packages/client/ui-layout/README.i18n.yaml | 4 +- packages/client/ui-layout/README.md | 2 +- packages/client/ui-layout/README.zh.md | 2 +- packages/client/ui-layout/src/client/index.ts | 1 + .../ui-layout/src/client/theme-presenter.ts | 20 +- .../tests/theme-presenter.client.spec.ts | 71 ++- .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 2 +- packages/client/ui-primitives/README.zh.md | 2 +- .../ui-primitives/src/TerminalBlock.tsx | 8 +- packages/client/ui-renderer/README.i18n.yaml | 12 +- packages/client/ui-renderer/README.md | 7 +- packages/client/ui-renderer/README.zh.md | 7 +- packages/client/ui-renderer/package.json | 5 +- .../client/ui-renderer/src/client/index.ts | 49 +- .../client/ui-renderer/src/client/renderer.ts | 115 +++++ .../src/client/styles/document-styles.ts | 189 ++++++++ .../tests/module-styles.client.spec.ts | 447 ++++++++++++++++++ .../tests/ui-renderer.client.spec.tsx | 213 ++++++++- packages/client/ui-renderer/tsconfig.json | 6 + packages/client/ui-theme/src/client/styles.ts | 41 +- .../tests/client-styles.client.spec.ts | 28 +- .../tests/client-bundle.client.spec.ts | 32 +- packages/client/web/README.i18n.yaml | 8 +- packages/client/web/README.md | 8 +- packages/client/web/README.zh.md | 8 +- packages/client/web/package.json | 1 + packages/client/web/src/boot.ts | 26 +- packages/client/web/src/platform.ts | 7 + packages/client/web/src/seed.ts | 63 +-- .../web/tests/boot-client.client.spec.ts | 4 +- packages/client/web/tests/boot.client.spec.ts | 5 + .../web/tests/source-static-modules.client.ts | 41 ++ packages/client/web/tsconfig.json | 1 + packages/client/web/tsdown.config.ts | 4 +- .../liveshare/tests/viewer-page.client.ts | 3 + .../skills/dsh-doc/references/packages.md | 2 + .../client-runtime/src/assembly/modules.ts | 2 +- .../assembly-bundle-roster.client.spec.ts | 4 +- .../tests/assembly-roster.client.spec.ts | 5 +- .../package-manifest/src/client-module.ts | 42 ++ packages/util/package-manifest/src/index.ts | 10 + pnpm-lock.yaml | 39 ++ scripts/browser-bundled-externals.spec.ts | 51 ++ scripts/browser-bundled-externals.ts | 3 +- scripts/client-bundle-css.spec.ts | 80 +++- scripts/client-bundle-purity.spec.ts | 189 +++++++- scripts/gen-cordis-catalog.ts | 1 + scripts/product-package-policy.ts | 2 + scripts/verify-client-packages.spec.ts | 28 ++ scripts/verify-client-packages.ts | 5 +- .../verify-package-readme-model-experience.ts | 2 + tsconfig.base.json | 4 + tsconfig.client.json | 2 + 146 files changed, 4410 insertions(+), 628 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-11-05-client-module-metadata.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-11-05-client-module-metadata.md create mode 100644 .agents/notes/implemented/architecture/2026-11-05-client-module-metadata.zh.md create mode 100644 apps/web/tests/source-static-modules.client.ts create mode 100644 docs/upgrade-guide/v0.2.2-rc.2/client-module-metadata/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.2/client-module-metadata/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.2/client-module-metadata/guide.zh.md create mode 100644 packages/client/modules/src/client/main-realm.ts create mode 100644 packages/client/modules/tests/document-module.client.spec.ts create mode 100644 packages/client/modules/tests/main-realm.client.spec.ts create mode 100644 packages/client/script-realm-iframe/README.i18n.yaml create mode 100644 packages/client/script-realm-iframe/README.md create mode 100644 packages/client/script-realm-iframe/README.zh.md create mode 100644 packages/client/script-realm-iframe/locale/de.json create mode 100644 packages/client/script-realm-iframe/locale/en.json create mode 100644 packages/client/script-realm-iframe/locale/es.json create mode 100644 packages/client/script-realm-iframe/locale/fr.json create mode 100644 packages/client/script-realm-iframe/locale/ja.json create mode 100644 packages/client/script-realm-iframe/locale/pt.json create mode 100644 packages/client/script-realm-iframe/locale/ru.json create mode 100644 packages/client/script-realm-iframe/locale/zh.json create mode 100644 packages/client/script-realm-iframe/package.json create mode 100644 packages/client/script-realm-iframe/src/client/iframe.ts create mode 100644 packages/client/script-realm-iframe/src/client/index.ts create mode 100644 packages/client/script-realm-iframe/src/index.ts create mode 100644 packages/client/script-realm-iframe/tests/execution.client.spec.ts create mode 100644 packages/client/script-realm-iframe/tests/realm.client.spec.ts create mode 100644 packages/client/script-realm-iframe/tsconfig.json create mode 100644 packages/client/script-realm-iframe/tsdown.config.ts create mode 100644 packages/client/script-realm/README.i18n.yaml create mode 100644 packages/client/script-realm/README.md create mode 100644 packages/client/script-realm/README.zh.md create mode 100644 packages/client/script-realm/locale/de.json create mode 100644 packages/client/script-realm/locale/en.json create mode 100644 packages/client/script-realm/locale/es.json create mode 100644 packages/client/script-realm/locale/fr.json create mode 100644 packages/client/script-realm/locale/ja.json create mode 100644 packages/client/script-realm/locale/pt.json create mode 100644 packages/client/script-realm/locale/ru.json create mode 100644 packages/client/script-realm/locale/zh.json create mode 100644 packages/client/script-realm/package.json create mode 100644 packages/client/script-realm/src/client/index.ts create mode 100644 packages/client/script-realm/src/client/types.ts create mode 100644 packages/client/script-realm/src/index.ts create mode 100644 packages/client/script-realm/tests/realm.client.spec.ts create mode 100644 packages/client/script-realm/tsconfig.json create mode 100644 packages/client/script-realm/tsdown.config.ts create mode 100644 packages/client/ui-renderer/src/client/renderer.ts create mode 100644 packages/client/ui-renderer/src/client/styles/document-styles.ts create mode 100644 packages/client/ui-renderer/tests/module-styles.client.spec.ts create mode 100644 packages/client/web/tests/source-static-modules.client.ts create mode 100644 packages/util/package-manifest/src/client-module.ts diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml index a41dd3bd98..f29cf535f2 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml @@ -15,20 +15,20 @@ en: 6af228b03e5e533f zh: 276a522af6be5d7a /agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/one-module-system-one-plugin-governor: - en: 575aad62490f32e9 - zh: a6c18eb63965fc1e + en: 5f5daec51b20db77 + zh: e4d6f78fc1b4b835 /agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/combo-external-script-arrival-and-source-maps: en: 0a4240d88cca240a zh: 8f5f1527caf571cd /agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/the-loading-flow-end-to-end: - en: dd05aa1ee608c414 - zh: 2863ced0086e3122 + en: 1f7db6ecfc0b0831 + zh: f6bf37dc921a7d40 /agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/live-graph-reconciliation: - en: 37e2fa1fe5cb2b95 - zh: 80e513db87709cb4 + en: ab9577214d7b2f2b + zh: fc8f10fd8c90b34b /agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/hot-reload-one-driver-plugin-self-watched-bundles: - en: c1fdcb3e6f074a7a - zh: b08c7b1ff25acb09 + en: e6a0bee3d31cd2c6 + zh: 7f7384c5d1a74751 /agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/package-ownership: en: 94ca0d09e6fd1e3a zh: d5949a2bdec795ba diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md index 15c0a39295..bc24420a59 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md @@ -34,7 +34,7 @@ The web kernel remains framework-free and imports no dynamic package value. Modu The browser mirrors the host's division of labor. `dsh-client-modules` (`ClientModuleSystem`) takes the module-system seat that Node's internal ESM loader holds host-side; the same vendored `@cordisjs/plugin-loader` keeps the governance seat on both sides. The line between them in one sentence: **the module system owns module identity and bytes — how code arrives, registers, and becomes an exports; the Loader owns plugin lifecycle — when a plugin mounts, what it waits for, and how it is torn down.** -`ClientModuleSystem` is a lazy CJS table. Executing a bundle only **registers** its factory — an entry calls `window.__ModuleLoader__.load({ id, factory })`, while a chunk also supplies its generated filename — and nothing else happens. Every module body side effect, CSS injection included, lives inside the factory closure and runs at materialization: the first `require`/import of that id, memoized after that. Import and prefetch recursively register declared dynamic requests before their consumer; a factory then materializes any registered-but-unmaterialized request synchronously. The callable `require` resolves synchronous module-table requests; its `require.async` operation returns a Promise that loads, registers, and materializes one package-local chunk. The shared tsdown preset compiles source `import()` expressions for package-local chunks to that distinct operation. The supported output is self-contained: an entry or chunk cannot synchronously require another relative `client*.js` output. The table resolves through a fixed branch order: seed word → memoized record → graph-row classic-script registration → registered-factory materialization → loud throw. The modules factory is the bootstrap exception: the HTML facade materializes it first, and construction places those same exports directly in the memoized table. That final throw is the runtime mirror of the build-time purity gate. The system also keeps per-module bookkeeping — owned `