From c05771d82867f29182c4b01d5daaaff49cb15a6e Mon Sep 17 00:00:00 2001 From: winewill Date: Sun, 20 Sep 2026 14:17:51 +0800 Subject: [PATCH 01/27] build(desktop): isolate test downloads by release ID --- apps/desktop/.env.macos.example | 3 ++ apps/desktop/.env.windows.example | 3 ++ apps/desktop/README.i18n.yaml | 4 +- apps/desktop/README.md | 10 ++++- apps/desktop/README.zh.md | 10 ++++- .../desktop-auto-update-environment.d.mts | 9 +++-- .../desktop-auto-update-environment.mjs | 21 +++++++--- .../scripts/desktop-package-environment.mjs | 2 +- apps/desktop/scripts/desktop-upload-plan.ts | 2 +- .../desktop-auto-update-environment.spec.ts | 38 +++++++++++++++++-- .../tests/desktop-package-environment.spec.ts | 21 +++++++++- .../desktop/tests/desktop-upload-plan.spec.ts | 37 +++++++++++++++++- .../test-release-upload-mac-arm64.json | 19 ++++++++++ .../expected/test-release-upload-mac-x64.json | 19 ++++++++++ .../expected/test-release-upload-win-x64.json | 16 ++++++++ .../tests/installed-update-builder.spec.ts | 2 +- .../desktop/tests/installer-packaging.spec.ts | 2 +- apps/desktop/tests/macos-signature.spec.ts | 4 +- apps/desktop/tests/package-macos.spec.ts | 6 +-- .../tests/package-target-stages.spec.ts | 4 +- .../tests/upload-with-credentials.spec.ts | 2 +- .../desktop/tests/windows-asar-unpack.spec.ts | 2 +- apps/desktop/tests/windows-sign.spec.ts | 2 +- 23 files changed, 205 insertions(+), 33 deletions(-) create mode 100644 apps/desktop/tests/expected/test-release-upload-mac-arm64.json create mode 100644 apps/desktop/tests/expected/test-release-upload-mac-x64.json create mode 100644 apps/desktop/tests/expected/test-release-upload-win-x64.json diff --git a/apps/desktop/.env.macos.example b/apps/desktop/.env.macos.example index ef0f625950..e4bfc40676 100644 --- a/apps/desktop/.env.macos.example +++ b/apps/desktop/.env.macos.example @@ -3,6 +3,9 @@ DSH_DESKTOP_APP_ID=com.deepseek.harness DSH_DESKTOP_AUTO_UPDATE_ENV=test DOWNLOAD_TEST_ORIGIN= +# Required for test releases: 32 lowercase hexadecimal characters from a secure random generator. +# Generate once per release batch; keep the same value through packaging and upload retries. +DOWNLOAD_TEST_RELEASE_ID= # Workspace tarball workers; omit to use 4. Must be a positive integer. DSH_DESKTOP_MACOS_PACK_CONCURRENCY=4 diff --git a/apps/desktop/.env.windows.example b/apps/desktop/.env.windows.example index 9b38d46df9..7a8e0dd16b 100644 --- a/apps/desktop/.env.windows.example +++ b/apps/desktop/.env.windows.example @@ -3,6 +3,9 @@ DSH_DESKTOP_APP_ID=com.deepseek.harness DSH_DESKTOP_AUTO_UPDATE_ENV=test DOWNLOAD_TEST_ORIGIN= +# Required for test releases: 32 lowercase hexadecimal characters from a secure random generator. +# Generate once per release batch; keep the same value through packaging and upload retries. +DOWNLOAD_TEST_RELEASE_ID= # The selected mandatory-update origin is required, including unsigned and preparation builds. DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN= diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 455501862e..480b62fd0f 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write apps/desktop/README.md -README.md: 6c9a6a8784732e6fa1369df5632391b789786b22 -README.zh.md: a0f2184d911eeab46902670cf992b6847e2bca31 +README.md: 410c0539caa129ede9a4055cd098da13e5f9371c +README.zh.md: e9367d57088447e580b9ef58c7e35c89d69d8d6e diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 6c9a6a8784..410c0539ca 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -164,7 +164,7 @@ Test and production uploads through `upload:*` retain a fresh `.desktop-build/up Windows operators can keep a CLIXML object with DPAPI-encrypted `SecretId` and `SecretKey` SecureString fields outside the repository. The [credential launcher](scripts/upload-with-credentials.ps1) requires an explicit `-CredentialFile` and `-Environment production` or `test`; without `-Upload`, it only verifies decryption and injection into a local Node child, with no network request. It requires Node on `PATH` and the Windows user and machine that encrypted the file. Plaintext, empty, and whitespace-only fields fail. The parent environment is unchanged; the child receives only the selected COS pair after unrelated secrets and Node preload options are removed. Raw child stderr is suppressed and credential values in stdout are redacted. This check does not prove COS authorization. An explicit upload additionally requires `-Upload -Target -Bucket ` and the normal completed-release prerequisites below; actual cloud upload remains release-operator qualification. This launcher supports permanent keys, not STS credentials. An explicit upload requires the selected deployment and bucket to match the target dotenv and completed package record before network writes; it uses the DPAPI credential pair even if the dotenv contains other COS keys. -`DSH_DESKTOP_AUTO_UPDATE_ENV` selects `test` or `production` for both the URL embedded during packaging and the later COS upload; an absent value selects `test`. Test packaging requires its HTTPS origin in `DOWNLOAD_TEST_ORIGIN`; production uses `https://download.deepseek.com`. Upload requires the selected bucket in `DOWNLOAD_TEST_COS_BUCKET` or `DOWNLOAD_PROD_COS_BUCKET`. Feed directories are `dsh-desk/feeds//`; versioned packages and blockmaps live in `dsh-desk/bin//`. Targets are `mac-arm64`, `mac-x64`, and `win-x64`. +`DSH_DESKTOP_AUTO_UPDATE_ENV` selects `test` or `production` for both the URL embedded during packaging and the later COS upload; an absent value selects `test`. Test packaging requires its HTTPS origin in `DOWNLOAD_TEST_ORIGIN`; production uses `https://download.deepseek.com`. Upload requires the selected bucket in `DOWNLOAD_TEST_COS_BUCKET` or `DOWNLOAD_PROD_COS_BUCKET`. Production feeds use `dsh-desk/feeds//` and binaries use `dsh-desk/bin//`. Test releases require `DOWNLOAD_TEST_RELEASE_ID`: 32 lowercase hexadecimal characters inserted as `dsh-desk//feeds//` and `dsh-desk//bin//`. YAML references, stable-channel aliases, and blockmaps stay inside that release directory. Targets are `mac-arm64`, `mac-x64`, and `win-x64`. The update destination and upload credentials follow the selected deployment: @@ -173,6 +173,14 @@ The update destination and upload credentials follow the selected deployment: | `test` or unset | `DOWNLOAD_TEST_ORIGIN` | `DOWNLOAD_TEST_COS_BUCKET` | `DOWNLOAD_TEST_COS_SECRET_ID`, `DOWNLOAD_TEST_COS_SECRET_KEY` | | `production` | `https://download.deepseek.com` | `DOWNLOAD_PROD_COS_BUCKET` | `DOWNLOAD_PROD_COS_SECRET_ID`, `DOWNLOAD_PROD_COS_SECRET_KEY` | +Generate a fresh ID for each test release batch with the command below and copy its output into `DOWNLOAD_TEST_RELEASE_ID` in `.env.macos` or `.env.windows`. These Git-ignored platform files own the value; shell variables do not override it, and dotenv values are not shell-expanded. Keep the ID through packaging, upload, and retries; upload rejects a completion record with a different update URL. Production does not use this field. + +```sh +node --input-type=module -e 'import { randomBytes } from "node:crypto"; console.log(randomBytes(16).toString("hex"))' +``` + +Distribute each test batch through its complete download links. Installed test clients retain their batch feed and do not discover a new ID automatically. Random paths reduce guessing, not access by link holders; withdrawing a batch requires deleting its COS objects and purging its CDN directory. + Configure the update origin and selected COS bucket, SecretId, and SecretKey in the target dotenv file, then package and upload the same target: ```sh diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index a0f2184d91..e9367d5708 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -164,7 +164,7 @@ test 与 production 的 `upload:*` 上传在发布前置检查通过后,分别 Windows 操作人员可以在仓库外保存 CLIXML 对象,其中 `SecretId` 和 `SecretKey` 是经 DPAPI 加密的 SecureString 字段。[凭据启动器](scripts/upload-with-credentials.ps1)要求显式提供 `-CredentialFile` 和 `-Environment production` 或 `test`;不指定 `-Upload` 时,只验证解密以及向本地 Node 子进程注入凭据,不发起网络请求。它要求 `PATH` 中有 Node,并使用加密该文件时的 Windows 用户和机器。明文、空字段及纯空白字段都会失败。父进程环境保持不变;子进程先清除无关密钥与 Node 预加载选项,再仅接收所选 COS 凭据对。原始子进程 stderr 不会显示,stdout 中的凭据值会被遮盖。此检查不能证明 COS 授权有效。显式上传还要求 `-Upload -Target -Bucket ` 及下述常规发布完成前提;真实云端上传仍需发布操作人员验收。此启动器支持长期密钥,不支持 STS 凭据。显式上传要求所选部署环境和 bucket 与目标 dotenv 文件及已完成的打包记录一致,才会发起网络写入;即使 dotenv 文件含有其他 COS 密钥,也使用 DPAPI 凭据对。 -`DSH_DESKTOP_AUTO_UPDATE_ENV` 同时选择打包写入的 URL 与后续 COS 上传环境,可取 `test` 或 `production`;缺省为 `test`。测试打包通过 `DOWNLOAD_TEST_ORIGIN` 提供 HTTPS origin;生产使用 `https://download.deepseek.com`。上传通过 `DOWNLOAD_TEST_COS_BUCKET` 或 `DOWNLOAD_PROD_COS_BUCKET` 提供所选 bucket。清单目录为 `dsh-desk/feeds//`;带版本的安装包和 blockmap 位于 `dsh-desk/bin//`。目标为 `mac-arm64`、`mac-x64` 和 `win-x64`。 +`DSH_DESKTOP_AUTO_UPDATE_ENV` 同时选择打包写入的 URL 与后续 COS 上传环境,可取 `test` 或 `production`;缺省为 `test`。测试打包通过 `DOWNLOAD_TEST_ORIGIN` 提供 HTTPS origin;生产使用 `https://download.deepseek.com`。上传通过 `DOWNLOAD_TEST_COS_BUCKET` 或 `DOWNLOAD_PROD_COS_BUCKET` 提供所选 bucket。生产清单位于 `dsh-desk/feeds//`,安装包位于 `dsh-desk/bin//`。测试发布必须配置 `DOWNLOAD_TEST_RELEASE_ID`:32 位小写十六进制字符,分别插入路径 `dsh-desk//feeds//` 和 `dsh-desk//bin//`。YAML 引用、稳定通道别名和 blockmap 都位于该发布目录内。目标为 `mac-arm64`、`mac-x64` 和 `win-x64`。 更新目标与上传凭据都与所选环境对应: @@ -173,6 +173,14 @@ Windows 操作人员可以在仓库外保存 CLIXML 对象,其中 `SecretId` | `test` 或未设置 | `DOWNLOAD_TEST_ORIGIN` | `DOWNLOAD_TEST_COS_BUCKET` | `DOWNLOAD_TEST_COS_SECRET_ID`、`DOWNLOAD_TEST_COS_SECRET_KEY` | | `production` | `https://download.deepseek.com` | `DOWNLOAD_PROD_COS_BUCKET` | `DOWNLOAD_PROD_COS_SECRET_ID`、`DOWNLOAD_PROD_COS_SECRET_KEY` | +每个测试发布批次用下方命令生成新 ID,将输出填入 `.env.macos` 或 `.env.windows` 的 `DOWNLOAD_TEST_RELEASE_ID`。这两个被 Git 忽略的平台文件管理该值,shell 变量不能覆盖它,dotenv 值也不会进行 shell 展开。打包、上传和重试必须沿用同一个 ID;上传会拒绝更新 URL 不一致的完成记录。生产环境不使用该字段。 + +```sh +node --input-type=module -e 'import { randomBytes } from "node:crypto"; console.log(randomBytes(16).toString("hex"))' +``` + +通过完整下载链接分发每个测试批次。已安装的测试客户端保留当前批次的清单地址,不会自动发现新 ID。随机路径降低被猜中的概率,不限制持有链接者访问;撤下批次需要删除其 COS 对象并清除对应 CDN 目录缓存。 + 在目标 `.env` 中配置更新地址与所选 COS bucket、SecretId、SecretKey,再打包并上传同一个目标: ```sh diff --git a/apps/desktop/scripts/desktop-auto-update-environment.d.mts b/apps/desktop/scripts/desktop-auto-update-environment.d.mts index b1661646e5..00ebf8c5c0 100644 --- a/apps/desktop/scripts/desktop-auto-update-environment.d.mts +++ b/apps/desktop/scripts/desktop-auto-update-environment.d.mts @@ -7,13 +7,14 @@ export type DesktopAutoUpdateEnvironment = 'test' | 'production' /** Directory name of one supported Desktop release target. */ export type DesktopAutoUpdateTarget = 'mac-arm64' | 'mac-x64' | 'win-x64' -/** Public updater URL for one release target. */ +/** Public updater URL and object prefixes for one release target. */ export interface DesktopAutoUpdateConfig { readonly environment: DesktopAutoUpdateEnvironment readonly target: DesktopAutoUpdateTarget readonly origin: string readonly publicUrl: string readonly keyPrefix: string + readonly binaryKeyPrefix: string } /** Public updater URL and private COS destination for one upload target. */ @@ -62,12 +63,12 @@ export function desktopUpdateMetadataFilename( ): string /** - * Resolve the public updater URL for one release target. + * Resolve the public updater URL and object prefixes for one release target. * @param env - Packaging or upload environment. * @param platform - Target Node.js platform. * @param arch - Target Node.js architecture. * @returns Resolved updater configuration. - * @throws When the test deployment lacks a valid HTTPS origin. + * @throws When the test deployment lacks a valid HTTPS origin or a 32-character lowercase hexadecimal release ID. */ export function resolveDesktopAutoUpdateConfig( env: NodeJS.ProcessEnv, @@ -81,7 +82,7 @@ export function resolveDesktopAutoUpdateConfig( * @param platform - Target Node.js platform. * @param arch - Target Node.js architecture. * @returns Resolved upload configuration. - * @throws When the selected deployment lacks a required origin or bucket, or the test origin is not HTTPS. + * @throws When the selected deployment lacks a bucket or valid updater configuration. */ export function resolveDesktopUploadConfig( env: NodeJS.ProcessEnv, diff --git a/apps/desktop/scripts/desktop-auto-update-environment.mjs b/apps/desktop/scripts/desktop-auto-update-environment.mjs index eebd20156a..464d079b4d 100644 --- a/apps/desktop/scripts/desktop-auto-update-environment.mjs +++ b/apps/desktop/scripts/desktop-auto-update-environment.mjs @@ -120,12 +120,12 @@ function httpsOrigin(value, name) { } /** - * Resolve the public updater URL for one release target. + * Resolve the public updater URL and object prefixes for one release target. * @param {NodeJS.ProcessEnv} env - Packaging or upload environment. * @param {NodeJS.Platform} platform - Target Node.js platform. * @param {string} arch - Target Node.js architecture. - * @returns {{ environment: 'test' | 'production', target: 'mac-arm64' | 'mac-x64' | 'win-x64', origin: string, publicUrl: string, keyPrefix: string }} Resolved updater configuration. - * @throws {Error} When the test deployment lacks a valid HTTPS origin. + * @returns {{ environment: 'test' | 'production', target: 'mac-arm64' | 'mac-x64' | 'win-x64', origin: string, publicUrl: string, keyPrefix: string, binaryKeyPrefix: string }} Resolved updater configuration. + * @throws {Error} When the test deployment lacks a valid HTTPS origin or a 32-character lowercase hexadecimal release ID. */ export function resolveDesktopAutoUpdateConfig(env, platform, arch) { const environment = resolveDesktopAutoUpdateEnvironment(env) @@ -137,12 +137,21 @@ export function resolveDesktopAutoUpdateConfig(env, platform, arch) { if (originEnvName === undefined) throw new Error('desktop auto-update: selected deployment has no origin') origin = httpsOrigin(requiredEnvironmentValue(env, originEnvName), originEnvName) } - const keyPrefix = `dsh-desk/feeds/${target}` + let releasePrefix = 'dsh-desk' + if (environment === 'test') { + const releaseId = requiredEnvironmentValue(env, 'DOWNLOAD_TEST_RELEASE_ID') + if (!/^[a-f0-9]{32}$/u.test(releaseId)) { + throw new Error('desktop auto-update: DOWNLOAD_TEST_RELEASE_ID must contain 32 lowercase hexadecimal characters') + } + releasePrefix += `/${releaseId}` + } + const keyPrefix = `${releasePrefix}/feeds/${target}` return { environment, target, origin, keyPrefix, + binaryKeyPrefix: `${releasePrefix}/bin/${target}`, publicUrl: `${origin}/${keyPrefix}/`, } } @@ -152,8 +161,8 @@ export function resolveDesktopAutoUpdateConfig(env, platform, arch) { * @param {NodeJS.ProcessEnv} env - Upload environment. * @param {NodeJS.Platform} platform - Target Node.js platform. * @param {string} arch - Target Node.js architecture. - * @returns {{ environment: 'test' | 'production', target: 'mac-arm64' | 'mac-x64' | 'win-x64', origin: string, publicUrl: string, keyPrefix: string, bucket: string, secretIdEnvName: string, secretKeyEnvName: string }} Resolved upload configuration. - * @throws {Error} When the selected deployment lacks a required origin or bucket, or the test origin is not HTTPS. + * @returns {{ environment: 'test' | 'production', target: 'mac-arm64' | 'mac-x64' | 'win-x64', origin: string, publicUrl: string, keyPrefix: string, binaryKeyPrefix: string, bucket: string, secretIdEnvName: string, secretKeyEnvName: string }} Resolved upload configuration. + * @throws {Error} When the selected deployment lacks a bucket or valid updater configuration. */ export function resolveDesktopUploadConfig(env, platform, arch) { const update = resolveDesktopAutoUpdateConfig(env, platform, arch) diff --git a/apps/desktop/scripts/desktop-package-environment.mjs b/apps/desktop/scripts/desktop-package-environment.mjs index c8a794e3c7..8fe35b60bf 100644 --- a/apps/desktop/scripts/desktop-package-environment.mjs +++ b/apps/desktop/scripts/desktop-package-environment.mjs @@ -12,7 +12,7 @@ import { resolveMacOSPackageSettings } from './macos-package-settings.mjs' import { resolveWindowsSignatureCacheDirectory } from './windows-signature-cache-directory.mjs' const APP_ROOT = fileURLToPath(new URL('..', import.meta.url)) -const SHARED_SETTING = /^(?:DSH_DESKTOP_(?:APP_ID|AUTO_UPDATE_ENV|MANDATORY_UPDATE_(?:CONFIG|(?:TEST|PROD)_ORIGIN))|DOWNLOAD_(?:TEST|PROD)_(?:ORIGIN|COS_BUCKET|COS_SECRET_ID|COS_SECRET_KEY))$/u +const SHARED_SETTING = /^(?:DSH_DESKTOP_(?:APP_ID|AUTO_UPDATE_ENV|MANDATORY_UPDATE_(?:CONFIG|(?:TEST|PROD)_ORIGIN))|DOWNLOAD_TEST_RELEASE_ID|DOWNLOAD_(?:TEST|PROD)_(?:ORIGIN|COS_BUCKET|COS_SECRET_ID|COS_SECRET_KEY))$/u const WINDOWS_SETTING = /^DSH_DESKTOP_WINDOWS_(?:CER_FILE|SIGNTOOL|KEY_CONTAINER|TOKEN_PIN|SIGNATURE_CACHE_DIR)$/u const MACOS_SETTING = /^(?:DSH_DESKTOP_MACOS_(?:SIGNING_IDENTITY|TEAM_ID|PACK_CONCURRENCY|DOWNLOAD_PROXY|NOTARIZATION_PROXY)|APPLE_(?:API_KEY|API_KEY_ID|API_ISSUER|ID|APP_SPECIFIC_PASSWORD|TEAM_ID|KEYCHAIN|KEYCHAIN_PROFILE)|CSC_(?:LINK|KEY_PASSWORD))$/u const AMBIENT_RELEASE_SETTING = /^(?:DSH_DESKTOP_(?:APP_ID|AUTO_UPDATE_ENV|MANDATORY_UPDATE_.*|WINDOWS_.*|MACOS_.*)|APPLE_.*|(?:WIN_)?CSC_.*|DOWNLOAD_(?:TEST|PROD)_.*)$/iu diff --git a/apps/desktop/scripts/desktop-upload-plan.ts b/apps/desktop/scripts/desktop-upload-plan.ts index 0ec76dba3a..32f891dcc8 100644 --- a/apps/desktop/scripts/desktop-upload-plan.ts +++ b/apps/desktop/scripts/desktop-upload-plan.ts @@ -222,7 +222,7 @@ export async function createDesktopUploadPlan( const updaterInfo = updateFileInfo(metadata.files[0], `${metadataFilename}.files[0]`, `${base}.${updaterExtension}`) const updaterPath = await verifyChecksummedArtifact(artifactsRoot, updaterInfo) const artifacts: DesktopUploadArtifact[] = [] - const binaryPrefix = `dsh-desk/bin/${targetName}` + const binaryPrefix = update.binaryKeyPrefix if (target.platform === 'darwin') { const dmgPath = await requireArtifact(artifactsRoot, `${base}.dmg`) diff --git a/apps/desktop/tests/desktop-auto-update-environment.spec.ts b/apps/desktop/tests/desktop-auto-update-environment.spec.ts index 747657042b..c33a9384df 100644 --- a/apps/desktop/tests/desktop-auto-update-environment.spec.ts +++ b/apps/desktop/tests/desktop-auto-update-environment.spec.ts @@ -8,20 +8,48 @@ import { resolveDesktopUploadConfig, } from '../scripts/desktop-auto-update-environment.mjs' +const RELEASE_ID = '0123456789abcdef0123456789abcdef' + describe('desktop auto-update environment', () => { + it.each([undefined, 'test'])('requires a release ID for deployment %s', (deployment) => { + const environment = { DSH_DESKTOP_AUTO_UPDATE_ENV: deployment, DOWNLOAD_TEST_ORIGIN: 'https://updates.example.com', + DOWNLOAD_TEST_COS_BUCKET: 'test-bucket' } + expect(() => resolveDesktopAutoUpdateConfig(environment, 'win32', 'x64')).toThrow(/DOWNLOAD_TEST_RELEASE_ID/u) + expect(() => resolveDesktopUploadConfig(environment, 'win32', 'x64')).toThrow(/DOWNLOAD_TEST_RELEASE_ID/u) + }) + + it.each(['', ' ', 'release-1', 'a'.repeat(31), 'a'.repeat(33), 'A'.repeat(32), 'g'.repeat(32), + '../feeds', '01234567-89ab-cdef-0123-456789abcdef', `${RELEASE_ID}/bin`])('rejects invalid test release ID %j', (id) => { + const environment = { DOWNLOAD_TEST_ORIGIN: 'https://updates.example.com', DOWNLOAD_TEST_RELEASE_ID: id } + expect(() => resolveDesktopAutoUpdateConfig(environment, 'darwin', 'arm64')).toThrow(/DOWNLOAD_TEST_RELEASE_ID/u) + }) + + it.each([['darwin', 'arm64', 'mac-arm64'], ['darwin', 'x64', 'mac-x64'], ['win32', 'x64', 'win-x64']] as const) + ('uses one test release directory for %s %s feeds and binaries', (platform, arch, target) => { + expect(resolveDesktopAutoUpdateConfig({ DOWNLOAD_TEST_ORIGIN: 'https://updates.example.com', + DOWNLOAD_TEST_RELEASE_ID: RELEASE_ID }, platform, arch)).toMatchObject({ + publicUrl: `https://updates.example.com/dsh-desk/${RELEASE_ID}/feeds/${target}/`, + keyPrefix: `dsh-desk/${RELEASE_ID}/feeds/${target}`, + binaryKeyPrefix: `dsh-desk/${RELEASE_ID}/bin/${target}`, + }) + }) + it('defaults packages and uploads to the test deployment', () => { expect(resolveDesktopAutoUpdateEnvironment({})).toBe('test') expect(resolveDesktopAutoUpdateConfig({ DOWNLOAD_TEST_ORIGIN: 'https://desktop-updates.example.com/', + DOWNLOAD_TEST_RELEASE_ID: RELEASE_ID, }, 'darwin', 'arm64')).toEqual({ environment: 'test', target: 'mac-arm64', origin: 'https://desktop-updates.example.com', - publicUrl: 'https://desktop-updates.example.com/dsh-desk/feeds/mac-arm64/', - keyPrefix: 'dsh-desk/feeds/mac-arm64', + publicUrl: `https://desktop-updates.example.com/dsh-desk/${RELEASE_ID}/feeds/mac-arm64/`, + keyPrefix: `dsh-desk/${RELEASE_ID}/feeds/mac-arm64`, + binaryKeyPrefix: `dsh-desk/${RELEASE_ID}/bin/mac-arm64`, }) expect(resolveDesktopUploadConfig({ DOWNLOAD_TEST_ORIGIN: 'https://desktop-updates.example.com/', + DOWNLOAD_TEST_RELEASE_ID: RELEASE_ID, DOWNLOAD_TEST_COS_BUCKET: 'test-download-bucket', }, 'darwin', 'arm64')).toMatchObject({ bucket: 'test-download-bucket', @@ -30,13 +58,15 @@ describe('desktop auto-update environment', () => { }) }) - it('selects the production URL for packages and bucket for uploads', () => { + it.each([undefined, RELEASE_ID, 'unused-test-value'])('keeps production paths independent of test release ID %s', (id) => { expect(resolveDesktopAutoUpdateConfig({ DSH_DESKTOP_AUTO_UPDATE_ENV: 'production', + DOWNLOAD_TEST_RELEASE_ID: id, }, 'win32', 'x64')).toMatchObject({ environment: 'production', target: 'win-x64', publicUrl: 'https://download.deepseek.com/dsh-desk/feeds/win-x64/', + binaryKeyPrefix: 'dsh-desk/bin/win-x64', }) expect(resolveDesktopUploadConfig({ DSH_DESKTOP_AUTO_UPDATE_ENV: 'production', @@ -53,9 +83,11 @@ describe('desktop auto-update environment', () => { .toThrow(/DOWNLOAD_TEST_ORIGIN/u) expect(resolveDesktopAutoUpdateConfig({ DOWNLOAD_TEST_ORIGIN: 'https://desktop-updates.example.com', + DOWNLOAD_TEST_RELEASE_ID: RELEASE_ID, }, 'darwin', 'arm64').publicUrl).toContain('/mac-arm64/') expect(() => resolveDesktopUploadConfig({ DOWNLOAD_TEST_ORIGIN: 'https://desktop-updates.example.com', + DOWNLOAD_TEST_RELEASE_ID: RELEASE_ID, }, 'darwin', 'arm64')).toThrow(/DOWNLOAD_TEST_COS_BUCKET/u) expect(() => resolveDesktopUploadConfig({ DSH_DESKTOP_AUTO_UPDATE_ENV: 'production', diff --git a/apps/desktop/tests/desktop-package-environment.spec.ts b/apps/desktop/tests/desktop-package-environment.spec.ts index 7153f135a3..98d93e0c07 100644 --- a/apps/desktop/tests/desktop-package-environment.spec.ts +++ b/apps/desktop/tests/desktop-package-environment.spec.ts @@ -8,7 +8,8 @@ const WINDOWS = { platform: 'win32', arch: 'x64' } as const const MACOS = { platform: 'darwin', arch: 'arm64' } as const const POLICY = { DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com', DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }) } -const RELEASE = { ...POLICY, DSH_DESKTOP_APP_ID: 'com.example.desktop', DOWNLOAD_TEST_ORIGIN: 'https://updates.example.com' } +const RELEASE = { ...POLICY, DSH_DESKTOP_APP_ID: 'com.example.desktop', DOWNLOAD_TEST_ORIGIN: 'https://updates.example.com', + DOWNLOAD_TEST_RELEASE_ID: '0123456789abcdef0123456789abcdef' } const MAC_IDENTITY = { DSH_DESKTOP_MACOS_SIGNING_IDENTITY: 'Example Company (TEAMID1234)', DSH_DESKTOP_MACOS_TEAM_ID: 'TEAMID1234' } async function withDirectory(action: (directory: string) => Promise): Promise { @@ -33,6 +34,7 @@ describe('Desktop local packaging configuration', () => { dsh_desktop_mandatory_update_prod_origin: 'https://stale.example.com', DSH_DESKTOP_WINDOWS_TOKEN_PIN: 'stale-pin', APPLE_ID: 'stale-apple-id', CSC_LINK: 'stale-certificate', DOWNLOAD_TEST_ORIGIN: 'https://stale.example.com', + DOWNLOAD_TEST_RELEASE_ID: 'a'.repeat(32), download_test_release_id: 'b'.repeat(32), dsh_desktop_windows_key_container: 'case-insensitive-stale-container', } expect(loadDesktopPackageEnvironment('win32', parent, directory)).toEqual({ @@ -49,6 +51,23 @@ describe('Desktop local packaging configuration', () => { }) }) + it.each(['win32', 'darwin'] as const)('owns the %s release ID in its platform file', async (platform) => { + await withDirectory(async (directory) => { + const settings = Object.entries(RELEASE).map(([name, value]) => `${name}='${value}'`).join('\n') + '\n' + const file = join(directory, platform === 'win32' ? '.env.windows' : '.env.macos') + const parent = { DOWNLOAD_TEST_RELEASE_ID: 'a'.repeat(32) } + await writeFile(file, settings) + expect(loadDesktopPackageEnvironment(platform, parent, directory).DOWNLOAD_TEST_RELEASE_ID).toBe(RELEASE.DOWNLOAD_TEST_RELEASE_ID) + await writeFile(file, settings.replace(`DOWNLOAD_TEST_RELEASE_ID='${RELEASE.DOWNLOAD_TEST_RELEASE_ID}'\n`, '')) + const missing = loadDesktopPackageEnvironment(platform, parent, directory) + expect(missing.DOWNLOAD_TEST_RELEASE_ID).toBeUndefined() + expect(() => { + validateDesktopPackageEnvironment(missing, platform === 'win32' ? WINDOWS : MACOS) + }).toThrow(/DOWNLOAD_TEST_RELEASE_ID/u) + expect(parent.DOWNLOAD_TEST_RELEASE_ID).toBe('a'.repeat(32)) + }) + }) + it('loads mandatory update origins and options only from the platform file without changing its parent', async () => { await withDirectory(async (directory) => { const windowsPolicy = JSON.stringify({ intervalMs: 5000, allowedPageOrigins: ['https://download.example.invalid'] }) diff --git a/apps/desktop/tests/desktop-upload-plan.spec.ts b/apps/desktop/tests/desktop-upload-plan.spec.ts index d65a44a923..bf4d68843c 100644 --- a/apps/desktop/tests/desktop-upload-plan.spec.ts +++ b/apps/desktop/tests/desktop-upload-plan.spec.ts @@ -12,6 +12,7 @@ import type { DesktopPackageTargetName } from '../scripts/package-target.ts' const temporaryDirectories: string[] = [] const TEST_ORIGIN = 'https://desktop-updates.example.com' const TEST_BUCKET = 'test-download-bucket' +const RELEASE_ID = '0123456789abcdef0123456789abcdef' const PRODUCTION_BUCKET = 'production-download-bucket' const require = createRequire(import.meta.url) const { createBlockmap } = require('app-builder-lib/out/targets/differentialUpdateInfoBuilder.js') as { @@ -54,7 +55,7 @@ async function fixture( target, version, environment, - publicUrl: `${origin}/dsh-desk/feeds/${target}/`, + publicUrl: `${origin}/dsh-desk/${environment === 'test' ? `${RELEASE_ID}/` : ''}feeds/${target}/`, })}\n`) if (os === 'mac') { @@ -64,6 +65,7 @@ async function fixture( await writeFile(join(artifactsRoot, `${base}.dmg`), 'notarized DMG fixture') await writeFile(join(artifactsRoot, desktopUpdateMetadataFilename(version, 'darwin')), `${JSON.stringify({ version, + path: `${base}.zip`, files: [{ url: `${base}.zip`, size: Buffer.byteLength(zip), sha512: digest(zip) }], })}\n`) } @@ -75,6 +77,7 @@ async function fixture( expect(Object.hasOwn(info, 'blockMapSize')).toBe(false) await writeFile(join(artifactsRoot, desktopUpdateMetadataFilename(version, 'win32')), `${JSON.stringify({ version, + path: `${base}.exe`, files: [{ url: `${base}.exe`, ...info, @@ -89,6 +92,7 @@ async function fixture( ? { DSH_DESKTOP_AUTO_UPDATE_ENV: 'test', DOWNLOAD_TEST_ORIGIN: TEST_ORIGIN, + DOWNLOAD_TEST_RELEASE_ID: RELEASE_ID, DOWNLOAD_TEST_COS_BUCKET: TEST_BUCKET, } : { @@ -132,7 +136,7 @@ describe('desktop upload plan', () => { expect(plan).toMatchObject({ environment: 'test', version: '1.2.3', - publicUrl: 'https://desktop-updates.example.com/dsh-desk/feeds/mac-arm64/', + publicUrl: `https://desktop-updates.example.com/dsh-desk/${RELEASE_ID}/feeds/mac-arm64/`, bucket: TEST_BUCKET, }) expect(plan.artifacts.map(artifact => artifact.filename)).toEqual([ @@ -147,6 +151,34 @@ describe('desktop upload plan', () => { }) }) + it.each(['mac-arm64', 'mac-x64', 'win-x64'] as const)('publishes every %s object and YAML reference inside the test release directory', async (target) => { + const paths = await fixture(target) + const plan = await createDesktopUploadPlan(target, paths) + const prefix = `dsh-desk/${RELEASE_ID}` + const payload = plan.artifacts.find(artifact => artifact.filename.endsWith(target === 'win-x64' ? '.exe' : '.zip'))! + for (const artifact of plan.artifacts) { + expect(artifact.key).toBe(`${prefix}/${artifact.channelMetadata ? 'feeds' : 'bin'}/${target}/${artifact.filename}`) + if (artifact.channelMetadata) { + expect(load(artifact.contents!)).toMatchObject({ + path: `${TEST_ORIGIN}/${payload.key}`, + files: [{ url: `${TEST_ORIGIN}/${payload.key}` }], + }) + } + } + await expect(JSON.stringify(plan.artifacts.map(({ key, contents }) => ({ key, contents })), null, 2) + '\n') + .toMatchFileSnapshot(`./expected/test-release-upload-${target}.json`) + }) + + it('rejects a changed or missing release ID before uploading a completed package', async () => { + const paths = await fixture('mac-arm64') + await expect(createDesktopUploadPlan('mac-arm64', { + ...paths, environment: { ...paths.environment, DOWNLOAD_TEST_RELEASE_ID: 'a'.repeat(32) }, + })).rejects.toThrow(/completion record/u) + await expect(createDesktopUploadPlan('mac-arm64', { + ...paths, environment: { ...paths.environment, DOWNLOAD_TEST_RELEASE_ID: undefined }, + })).rejects.toThrow(/DOWNLOAD_TEST_RELEASE_ID/u) + }) + it('uploads the prerelease channel metadata emitted by electron-builder', async () => { const paths = await fixture('mac-arm64', '1.2.3-alpha.4') const plan = await createDesktopUploadPlan('mac-arm64', paths) @@ -193,6 +225,7 @@ describe('desktop upload plan', () => { environment: { DSH_DESKTOP_AUTO_UPDATE_ENV: 'test', DOWNLOAD_TEST_ORIGIN: TEST_ORIGIN, + DOWNLOAD_TEST_RELEASE_ID: RELEASE_ID, DOWNLOAD_TEST_COS_BUCKET: TEST_BUCKET, }, })).rejects.toThrow(/completion record.*test/u) diff --git a/apps/desktop/tests/expected/test-release-upload-mac-arm64.json b/apps/desktop/tests/expected/test-release-upload-mac-arm64.json new file mode 100644 index 0000000000..515f0234f9 --- /dev/null +++ b/apps/desktop/tests/expected/test-release-upload-mac-arm64.json @@ -0,0 +1,19 @@ +[ + { + "key": "dsh-desk/0123456789abcdef0123456789abcdef/bin/mac-arm64/deepseek-harness-1.2.3-mac-arm64.dmg" + }, + { + "key": "dsh-desk/0123456789abcdef0123456789abcdef/bin/mac-arm64/deepseek-harness-1.2.3-mac-arm64.zip" + }, + { + "key": "dsh-desk/0123456789abcdef0123456789abcdef/bin/mac-arm64/deepseek-harness-1.2.3-mac-arm64.zip.blockmap" + }, + { + "key": "dsh-desk/0123456789abcdef0123456789abcdef/feeds/mac-arm64/nightly-mac.yml", + "contents": "version: 1.2.3\npath: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/mac-arm64/deepseek-harness-1.2.3-mac-arm64.zip\nfiles:\n - url: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/mac-arm64/deepseek-harness-1.2.3-mac-arm64.zip\n size: 24\n sha512: >-\n IgtiHRPFjickTxiSTW6k0ltyBNOF/gpMGj/xflzVV2iRIzUSFPY6BG45u9fR4GmAJSVtN+FMh3NZx7mddUfJLw==\n" + }, + { + "key": "dsh-desk/0123456789abcdef0123456789abcdef/feeds/mac-arm64/latest-mac.yml", + "contents": "version: 1.2.3\npath: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/mac-arm64/deepseek-harness-1.2.3-mac-arm64.zip\nfiles:\n - url: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/mac-arm64/deepseek-harness-1.2.3-mac-arm64.zip\n size: 24\n sha512: >-\n IgtiHRPFjickTxiSTW6k0ltyBNOF/gpMGj/xflzVV2iRIzUSFPY6BG45u9fR4GmAJSVtN+FMh3NZx7mddUfJLw==\n" + } +] diff --git a/apps/desktop/tests/expected/test-release-upload-mac-x64.json b/apps/desktop/tests/expected/test-release-upload-mac-x64.json new file mode 100644 index 0000000000..5039a3aede --- /dev/null +++ b/apps/desktop/tests/expected/test-release-upload-mac-x64.json @@ -0,0 +1,19 @@ +[ + { + "key": "dsh-desk/0123456789abcdef0123456789abcdef/bin/mac-x64/deepseek-harness-1.2.3-mac-x64.dmg" + }, + { + "key": "dsh-desk/0123456789abcdef0123456789abcdef/bin/mac-x64/deepseek-harness-1.2.3-mac-x64.zip" + }, + { + "key": "dsh-desk/0123456789abcdef0123456789abcdef/bin/mac-x64/deepseek-harness-1.2.3-mac-x64.zip.blockmap" + }, + { + "key": "dsh-desk/0123456789abcdef0123456789abcdef/feeds/mac-x64/nightly-mac.yml", + "contents": "version: 1.2.3\npath: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/mac-x64/deepseek-harness-1.2.3-mac-x64.zip\nfiles:\n - url: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/mac-x64/deepseek-harness-1.2.3-mac-x64.zip\n size: 24\n sha512: >-\n IgtiHRPFjickTxiSTW6k0ltyBNOF/gpMGj/xflzVV2iRIzUSFPY6BG45u9fR4GmAJSVtN+FMh3NZx7mddUfJLw==\n" + }, + { + "key": "dsh-desk/0123456789abcdef0123456789abcdef/feeds/mac-x64/latest-mac.yml", + "contents": "version: 1.2.3\npath: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/mac-x64/deepseek-harness-1.2.3-mac-x64.zip\nfiles:\n - url: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/mac-x64/deepseek-harness-1.2.3-mac-x64.zip\n size: 24\n sha512: >-\n IgtiHRPFjickTxiSTW6k0ltyBNOF/gpMGj/xflzVV2iRIzUSFPY6BG45u9fR4GmAJSVtN+FMh3NZx7mddUfJLw==\n" + } +] diff --git a/apps/desktop/tests/expected/test-release-upload-win-x64.json b/apps/desktop/tests/expected/test-release-upload-win-x64.json new file mode 100644 index 0000000000..cb60e0ce29 --- /dev/null +++ b/apps/desktop/tests/expected/test-release-upload-win-x64.json @@ -0,0 +1,16 @@ +[ + { + "key": "dsh-desk/0123456789abcdef0123456789abcdef/bin/win-x64/deepseek-harness-1.2.3-win-x64.exe" + }, + { + "key": "dsh-desk/0123456789abcdef0123456789abcdef/bin/win-x64/deepseek-harness-1.2.3-win-x64.exe.blockmap" + }, + { + "key": "dsh-desk/0123456789abcdef0123456789abcdef/feeds/win-x64/nightly.yml", + "contents": "version: 1.2.3\npath: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/win-x64/deepseek-harness-1.2.3-win-x64.exe\nfiles:\n - url: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/win-x64/deepseek-harness-1.2.3-win-x64.exe\n size: 30\n sha512: >-\n eVumVOW1yvT3fAgGKUnliEzSfhmn8jUfzpNaUPufU1yekWrwJe8wRPC+JOrHH2Hmc/eLynwxjX1yIiER8tVOTA==\n" + }, + { + "key": "dsh-desk/0123456789abcdef0123456789abcdef/feeds/win-x64/latest.yml", + "contents": "version: 1.2.3\npath: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/win-x64/deepseek-harness-1.2.3-win-x64.exe\nfiles:\n - url: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/win-x64/deepseek-harness-1.2.3-win-x64.exe\n size: 30\n sha512: >-\n eVumVOW1yvT3fAgGKUnliEzSfhmn8jUfzpNaUPufU1yekWrwJe8wRPC+JOrHH2Hmc/eLynwxjX1yIiER8tVOTA==\n" + } +] diff --git a/apps/desktop/tests/installed-update-builder.spec.ts b/apps/desktop/tests/installed-update-builder.spec.ts index 55ad22fd5d..089b04deef 100644 --- a/apps/desktop/tests/installed-update-builder.spec.ts +++ b/apps/desktop/tests/installed-update-builder.spec.ts @@ -18,7 +18,7 @@ vi.mock('../scripts/windows-sign.mjs', () => ({ })) const versions = ['0.1.6-nightly.20260914.1', '0.1.6-nightly.20260914.2'] as const -const environment = { DSH_DESKTOP_AUTO_UPDATE_ENV: 'test', DOWNLOAD_TEST_ORIGIN: 'https://download-test.deepseek.com', +const environment = { DSH_DESKTOP_AUTO_UPDATE_ENV: 'test', DOWNLOAD_TEST_ORIGIN: 'https://download-test.deepseek.com', DOWNLOAD_TEST_RELEASE_ID: '0123456789abcdef0123456789abcdef', DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com', DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }), DOWNLOAD_TEST_COS_BUCKET: 'bj-toc-download-test-1320056602' } diff --git a/apps/desktop/tests/installer-packaging.spec.ts b/apps/desktop/tests/installer-packaging.spec.ts index 1dcfcb24fd..75d6b02d7e 100644 --- a/apps/desktop/tests/installer-packaging.spec.ts +++ b/apps/desktop/tests/installer-packaging.spec.ts @@ -31,7 +31,7 @@ describe('installer preparation preserves application dependencies', () => { DSH_DESKTOP_MACOS_SIGNING_IDENTITY: 'Example Company (TEAMID1234)', DSH_DESKTOP_MACOS_TEAM_ID: 'TEAMID1234', APPLE_KEYCHAIN_PROFILE: 'installer-test', - DOWNLOAD_TEST_ORIGIN: 'https://desktop-updates.example.com', + DOWNLOAD_TEST_ORIGIN: 'https://desktop-updates.example.com', DOWNLOAD_TEST_RELEASE_ID: '0123456789abcdef0123456789abcdef', } for (const [name, value] of Object.entries(env)) vi.stubEnv(name, value) try { diff --git a/apps/desktop/tests/macos-signature.spec.ts b/apps/desktop/tests/macos-signature.spec.ts index 2bd63adbaa..4d71d3048b 100644 --- a/apps/desktop/tests/macos-signature.spec.ts +++ b/apps/desktop/tests/macos-signature.spec.ts @@ -22,7 +22,7 @@ const RELEASE_ENVIRONMENT = { APPLE_API_KEY: '/private/credentials/AuthKey_TEST123456.p8', APPLE_API_KEY_ID: 'TEST123456', APPLE_API_ISSUER: '11111111-2222-3333-4444-555555555555', - DOWNLOAD_TEST_ORIGIN: 'https://desktop-updates.example.com', + DOWNLOAD_TEST_ORIGIN: 'https://desktop-updates.example.com', DOWNLOAD_TEST_RELEASE_ID: '0123456789abcdef0123456789abcdef', } function portablePath(value: string): string { @@ -71,7 +71,7 @@ describe('desktop macOS release signature', () => { }, publish: [{ provider: 'generic', - url: 'https://desktop-updates.example.com/dsh-desk/feeds/mac-arm64/', + url: 'https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/feeds/mac-arm64/', channel: 'nightly', }], }) diff --git a/apps/desktop/tests/package-macos.spec.ts b/apps/desktop/tests/package-macos.spec.ts index 3b780b8b06..e8fb5dcf34 100644 --- a/apps/desktop/tests/package-macos.spec.ts +++ b/apps/desktop/tests/package-macos.spec.ts @@ -17,7 +17,7 @@ const environment = { DSH_DESKTOP_MACOS_SIGNING_IDENTITY: 'Example Company (TEAMID1234)', DSH_DESKTOP_MACOS_TEAM_ID: 'TEAMID1234', APPLE_KEYCHAIN_PROFILE: 'fixture-profile', - DOWNLOAD_TEST_ORIGIN: 'https://desktop-updates.example.com', + DOWNLOAD_TEST_ORIGIN: 'https://desktop-updates.example.com', DOWNLOAD_TEST_RELEASE_ID: '0123456789abcdef0123456789abcdef', } function barrier() { @@ -33,7 +33,7 @@ async function fixture(arch: 'arm64' | 'x64' = 'arm64') { await mkdir(join(appPath, 'Contents', 'Resources'), { recursive: true }) await writeFile(join(appPath, 'payload'), 'signed content') await writeMacOSAppUpdateConfig(join(appPath, 'Contents', 'Resources'), { - publicUrl: `https://desktop-updates.example.com/dsh-desk/feeds/mac-${arch}/`, + publicUrl: `https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/feeds/mac-${arch}/`, }, 'deepseek-harness-updater') const version = '1.2.3-alpha.1' const base = `deepseek-harness-${version}-mac-${arch}` @@ -107,7 +107,7 @@ describe('parallel macOS artifacts', () => { .toEqual({ payload: 'signed content', appTicket: false }) expect(await readFile(join(f.appPath, 'ticket'), 'utf8')).toBe('accepted') expect(await readFile(join(f.appPath, 'Contents', 'Resources', 'app-update.yml'), 'utf8')) - .toContain(`/dsh-desk/feeds/mac-${arch}/`) + .toContain(`/dsh-desk/0123456789abcdef0123456789abcdef/feeds/mac-${arch}/`) expect((await readdir(f.root)).sort()).toEqual(['artifacts']) expect(f.apple.verifySignature).toHaveBeenCalledTimes(4) expect(f.apple.verifyNotarization).toHaveBeenCalledTimes(1) diff --git a/apps/desktop/tests/package-target-stages.spec.ts b/apps/desktop/tests/package-target-stages.spec.ts index 5b8880ce6a..9e8f98b4c8 100644 --- a/apps/desktop/tests/package-target-stages.spec.ts +++ b/apps/desktop/tests/package-target-stages.spec.ts @@ -29,7 +29,7 @@ vi.mock('node:fs', async importOriginal => ({ afterEach(() => { vi.unstubAllEnvs(); vi.clearAllMocks() }) const environment = { DSH_DESKTOP_APP_ID: 'com.example.test', DSH_DESKTOP_AUTO_UPDATE_ENV: 'test', - DOWNLOAD_TEST_ORIGIN: 'https://updates.example.com', DSH_DESKTOP_WINDOWS_TOKEN_PIN: 'fixture-pin' } + DOWNLOAD_TEST_ORIGIN: 'https://updates.example.com', DOWNLOAD_TEST_RELEASE_ID: '0123456789abcdef0123456789abcdef', DSH_DESKTOP_WINDOWS_TOKEN_PIN: 'fixture-pin' } function supervisor(failure?: string) { vi.stubEnv('npm_execpath', 'fixture-pnpm.cjs') @@ -59,6 +59,8 @@ it('requires one signing preflight before building, then records only the comple } } expect(writeFileSync).toHaveBeenCalledOnce() + const record = JSON.parse(vi.mocked(writeFileSync).mock.calls[0]![1] as string) as { publicUrl: string } + expect(record.publicUrl).toBe('https://updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/feeds/win-x64/') }) it('initializes shared storage only after acquiring the preflight stage lock', async () => { diff --git a/apps/desktop/tests/upload-with-credentials.spec.ts b/apps/desktop/tests/upload-with-credentials.spec.ts index 9a6a93f0a8..29688621ca 100644 --- a/apps/desktop/tests/upload-with-credentials.spec.ts +++ b/apps/desktop/tests/upload-with-credentials.spec.ts @@ -86,7 +86,7 @@ afterEach(async () => { describe('credential launcher destination', () => { const fileEnvironment = { - DSH_DESKTOP_AUTO_UPDATE_ENV: 'test', DOWNLOAD_TEST_ORIGIN: 'https://download-test.example.com', + DSH_DESKTOP_AUTO_UPDATE_ENV: 'test', DOWNLOAD_TEST_ORIGIN: 'https://download-test.example.com', DOWNLOAD_TEST_RELEASE_ID: '0123456789abcdef0123456789abcdef', DOWNLOAD_TEST_COS_BUCKET: 'test-bucket', DOWNLOAD_TEST_COS_SECRET_ID: 'stale-id', DOWNLOAD_TEST_COS_SECRET_KEY: 'stale-key', } const injectedEnvironment = { diff --git a/apps/desktop/tests/windows-asar-unpack.spec.ts b/apps/desktop/tests/windows-asar-unpack.spec.ts index ddfaf15de2..2d5c79563b 100644 --- a/apps/desktop/tests/windows-asar-unpack.spec.ts +++ b/apps/desktop/tests/windows-asar-unpack.spec.ts @@ -168,7 +168,7 @@ it.each([true, false])('validates the real builder hook for unsigned=%s', async DSH_DESKTOP_APP_ID: 'com.example.unpack', DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com', DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }), DSH_DESKTOP_TARGET_PLATFORM: 'win32', DSH_DESKTOP_TARGET_ARCH: 'x64', DSH_DESKTOP_UNSIGNED: unsigned ? '1' : '0', - DSH_DESKTOP_WINDOWS_CER_FILE: certificate, DOWNLOAD_TEST_ORIGIN: 'https://updates.example.com', + DSH_DESKTOP_WINDOWS_CER_FILE: certificate, DOWNLOAD_TEST_ORIGIN: 'https://updates.example.com', DOWNLOAD_TEST_RELEASE_ID: '0123456789abcdef0123456789abcdef', }, 'win32', 'x64', input.source) // Qualification replaces files after creating the base configuration; builder owns a separate config object. input.config.asarUnpack = [...config.asarUnpack] diff --git a/apps/desktop/tests/windows-sign.spec.ts b/apps/desktop/tests/windows-sign.spec.ts index 1b1440b0fe..e5d5a7cd3f 100644 --- a/apps/desktop/tests/windows-sign.spec.ts +++ b/apps/desktop/tests/windows-sign.spec.ts @@ -159,7 +159,7 @@ describe('Windows token signing', () => { await writeFile(signTool, 'fixture') await writeFile(path, 'fixture') validateDesktopPackageEnvironment({ - DSH_DESKTOP_APP_ID: 'com.example.desktop', DOWNLOAD_TEST_ORIGIN: 'https://updates.example.com', + DSH_DESKTOP_APP_ID: 'com.example.desktop', DOWNLOAD_TEST_ORIGIN: 'https://updates.example.com', DOWNLOAD_TEST_RELEASE_ID: '0123456789abcdef0123456789abcdef', DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com', DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }), DSH_DESKTOP_WINDOWS_CER_FILE: certificateFile, DSH_DESKTOP_WINDOWS_SIGNTOOL: signTool, From 8e5073ee617532d0e526118d94aa13cbbf4b8d15 Mon Sep 17 00:00:00 2001 From: winewill Date: Sun, 20 Sep 2026 14:44:36 +0800 Subject: [PATCH 02/27] docs(desktop): clarify test release ID reuse and qualification --- ...08-25-electron-desktop-packaging-and-updates.i18n.yaml | 4 ++-- .../2026-08-25-electron-desktop-packaging-and-updates.md | 2 ++ ...026-08-25-electron-desktop-packaging-and-updates.zh.md | 2 ++ apps/desktop/.env.macos.example | 2 +- apps/desktop/.env.windows.example | 2 +- apps/desktop/README.i18n.yaml | 4 ++-- apps/desktop/README.md | 8 +++++--- apps/desktop/README.zh.md | 8 +++++--- apps/desktop/tests/installed-update/README.i18n.yaml | 4 ++-- apps/desktop/tests/installed-update/README.md | 2 +- apps/desktop/tests/installed-update/README.zh.md | 2 +- 11 files changed, 24 insertions(+), 16 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml index 6fa3c9e31b..6a9b597434 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md -2026-08-25-electron-desktop-packaging-and-updates.md: f58e8dc471faeb717dd79d32df4afc1b5cc3458f -2026-08-25-electron-desktop-packaging-and-updates.zh.md: 2d2d5c68f28974b606693d5b6727c864c92a0763 +2026-08-25-electron-desktop-packaging-and-updates.md: a985e1c91a1ccdb9c4aab0bc519974f9b6fafd4a +2026-08-25-electron-desktop-packaging-and-updates.zh.md: 17ace865477d4fae3650b56d6725be07c7bd0e0f diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md index f58e8dc471..a985e1c91a 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md +++ b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md @@ -75,6 +75,8 @@ The [immediate-window decision](2026-09-09-desktop-immediate-window-and-direct-s `DSH_DESKTOP_AUTO_UPDATE_ENV` selects the test deployment by default or the production deployment for both the target-specific generic-provider URL and COS destination. Release automation supplies the test HTTPS origin through `DOWNLOAD_TEST_ORIGIN` and each deployment's bucket through `DOWNLOAD_TEST_COS_BUCKET` or `DOWNLOAD_PROD_COS_BUCKET`; keeping mutable test routing and COS storage identities out of source lets deployment infrastructure change without a code release, while the public production origin remains fixed. Packaging resolves only the public updater URL, disables electron-builder publishing, removes every COS credential field from its subprocess environment, and writes a completion record only after electron-builder and every signing or notarization hook succeeds. Target upload additionally requires the selected bucket, then requires the completion record, root dsh version, Desktop version, version-derived channel metadata, artifact names, sizes, and SHA-512 values to agree before it reads the selected credentials or sends data. It uploads immutable versioned updater payloads and any separate blockmaps before replacing the channel metadata emitted by electron-builder, and it never deletes historical objects. Stable versions use the `latest` metadata name; prereleases use the first semantic-version prerelease identifier. NSIS embeds its blockmap in the signed executable; the macOS ZIP carries a separate blockmap. Both let electron-updater download changed blocks when supported, while application replacement and the local pnpm package operation remain separate operations. +Test releases require `DOWNLOAD_TEST_RELEASE_ID` from the platform dotenv file. Their feeds and binaries share `dsh-desk//`; production retains its fixed directories. The ID is part of the packaged update URL, so upload rejects a different ID. Internal distribution can supply a new installer after rotation; installed clients retain their existing feed. Random directories reduce guessing but provide no authorization for link holders. The [release configuration](../../../../apps/desktop/README.md#upload-updates) defines generation and reuse. + ## Security and release policy Core dsh and the private Desktop Host come only from the signed application resource tree. Plugin installation forwards package specs to pnpm, including local and remote sources, but never accepts raw pnpm commands. pnpm owns dependency resolution and the profile’s `allowBuilds` policy; the Host loads activated bundles. diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md index 2d2d5c68f2..17ace86547 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md @@ -75,6 +75,8 @@ Electron 更新只使用一个 `electron-updater` 发布流和签名 `electron-b `DSH_DESKTOP_AUTO_UPDATE_ENV` 默认为测试部署,也可以选择生产部署,并同时决定目标专用的 generic-provider URL 与 COS 目标。发布自动化通过 `DOWNLOAD_TEST_ORIGIN` 提供测试 HTTPS origin,并通过 `DOWNLOAD_TEST_COS_BUCKET` 或 `DOWNLOAD_PROD_COS_BUCKET` 提供各部署的 bucket;可变的测试路由与 COS 存储身份不写入源码,部署基础设施变更时无需发布新代码,而公开的生产 origin 仍固定。打包只解析公开更新 URL、禁止 electron-builder 发布、从子进程环境中删除每个 COS 凭据字段,并且只有在 electron-builder 以及每个签名或公证 hook 成功后才写入完成记录。目标上传还必须提供所选 bucket,随后会先要求完成记录、根 dsh 版本、Desktop 版本、根据版本得出的频道元数据、产物名称、大小与 SHA-512 全部一致,再读取所选凭据或发送数据。它先上传不可变且带版本的更新载荷与所有独立 blockmap,最后替换 electron-builder 生成的频道元数据,并且不会删除历史对象。稳定版本使用 `latest` 元数据名称,预发布版本则使用语义化版本的第一个预发布标识符。NSIS 把 blockmap 嵌入已签名的可执行文件,macOS ZIP 则使用独立 blockmap;两者都让 electron-updater 在平台支持时只下载变化的数据块,而应用替换与本地 pnpm 包操作仍是两个独立操作。 +测试发布必须从平台 dotenv 文件提供 `DOWNLOAD_TEST_RELEASE_ID`。清单和安装包共用 `dsh-desk//`,生产环境保留固定目录。ID 是打包更新 URL 的一部分,因此上传会拒绝不同的 ID。轮换后可通过内部分发提供新安装包,已安装客户端保留原清单地址。随机目录降低被猜中的概率,但不对持有链接者进行鉴权。[发布配置](../../../../apps/desktop/README.zh.md#upload-updates)定义生成与复用方式。 + ## 安全与发布策略 核心 dsh 和私有 Desktop Host 只来自签名应用的资源树。插件安装把包规格交给 pnpm,包括本地和远程来源,但不接受原始 pnpm 命令。pnpm 负责依赖解析和 profile 的 `allowBuilds` 策略;Host 加载已启用的 bundle。 diff --git a/apps/desktop/.env.macos.example b/apps/desktop/.env.macos.example index e4bfc40676..960e1195c5 100644 --- a/apps/desktop/.env.macos.example +++ b/apps/desktop/.env.macos.example @@ -4,7 +4,7 @@ DSH_DESKTOP_APP_ID=com.deepseek.harness DSH_DESKTOP_AUTO_UPDATE_ENV=test DOWNLOAD_TEST_ORIGIN= # Required for test releases: 32 lowercase hexadecimal characters from a secure random generator. -# Generate once per release batch; keep the same value through packaging and upload retries. +# Generate once per release batch; retain it for retries and versions testing upgrades within that batch. DOWNLOAD_TEST_RELEASE_ID= # Workspace tarball workers; omit to use 4. Must be a positive integer. diff --git a/apps/desktop/.env.windows.example b/apps/desktop/.env.windows.example index 7a8e0dd16b..b1001c6477 100644 --- a/apps/desktop/.env.windows.example +++ b/apps/desktop/.env.windows.example @@ -4,7 +4,7 @@ DSH_DESKTOP_APP_ID=com.deepseek.harness DSH_DESKTOP_AUTO_UPDATE_ENV=test DOWNLOAD_TEST_ORIGIN= # Required for test releases: 32 lowercase hexadecimal characters from a secure random generator. -# Generate once per release batch; keep the same value through packaging and upload retries. +# Generate once per release batch; retain it for retries and versions testing upgrades within that batch. DOWNLOAD_TEST_RELEASE_ID= # The selected mandatory-update origin is required, including unsigned and preparation builds. diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 480b62fd0f..b7937d5003 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write apps/desktop/README.md -README.md: 410c0539caa129ede9a4055cd098da13e5f9371c -README.zh.md: e9367d57088447e580b9ef58c7e35c89d69d8d6e +README.md: cd559119d80efbc66988063a947878d43775d5c8 +README.zh.md: 48fc783501f1d44a7a0d62152be5baaaa83357e7 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 410c0539ca..cd559119d8 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -158,6 +158,8 @@ pwsh -NoProfile -File apps/desktop/scripts/smoke-windows.ps1 -Makensis $Makensis The Windows installer extracts the new version beside the installation directory, stops the old application, and replaces directories through same-volume renames. Same-path upgrades preserve the old directory until promotion succeeds; extraction failure leaves it intact, and promotion failure attempts to restore it. The installer removes the old backup before launch. Forced termination or power loss can leave `.new-*` or `.old-*` directories; installation-location and scope migrations retain electron-builder's old-uninstaller flow. + + ### Upload updates Test and production uploads through `upload:*` retain a fresh `.desktop-build/upload-records/--*` directory after release preflight. `plan.json` records destination, version, every file's size/SHA-512, and published YAML bytes; flushed `events.jsonl` records PUT intent and available response status/request ID; `result.json` records completion or the last failed stage. A missing final result means interruption or unavailable storage, not success. No credential values, authorization headers, or raw SDK errors are recorded. Audit-write failures stop later PUTs. Every object is one streamed Tencent COS PUT with an explicit length and Content-MD5; the COS SDK repeats a request only when its body is not a stream, and this uploader does not retry either. Retain partial records and inspect remote state before another operation: a timeout or failed receipt write does not prove that the object was not stored. These records are local, not tamper-proof or automatically backed up; archive each release's records with its build evidence in controlled storage. Public CDN readback remains separate release qualification, explicitly marked `not-performed` in the upload result. @@ -173,13 +175,13 @@ The update destination and upload credentials follow the selected deployment: | `test` or unset | `DOWNLOAD_TEST_ORIGIN` | `DOWNLOAD_TEST_COS_BUCKET` | `DOWNLOAD_TEST_COS_SECRET_ID`, `DOWNLOAD_TEST_COS_SECRET_KEY` | | `production` | `https://download.deepseek.com` | `DOWNLOAD_PROD_COS_BUCKET` | `DOWNLOAD_PROD_COS_SECRET_ID`, `DOWNLOAD_PROD_COS_SECRET_KEY` | -Generate a fresh ID for each test release batch with the command below and copy its output into `DOWNLOAD_TEST_RELEASE_ID` in `.env.macos` or `.env.windows`. These Git-ignored platform files own the value; shell variables do not override it, and dotenv values are not shell-expanded. Keep the ID through packaging, upload, and retries; upload rejects a completion record with a different update URL. Production does not use this field. +Generate a fresh ID for each test release batch with the command below and copy its output into `DOWNLOAD_TEST_RELEASE_ID` in `.env.macos` or `.env.windows`. These Git-ignored platform files own the value; shell variables do not override it, and dotenv values are not shell-expanded. Keep the ID through packaging, upload, and retries; upload rejects a completion record with a different update URL. To test an upgrade between versions, reuse the installed client’s ID for the later version. Production does not use this field. ```sh -node --input-type=module -e 'import { randomBytes } from "node:crypto"; console.log(randomBytes(16).toString("hex"))' +node --input-type=module -e "import { randomBytes } from 'node:crypto'; console.log(randomBytes(16).toString('hex'))" ``` -Distribute each test batch through its complete download links. Installed test clients retain their batch feed and do not discover a new ID automatically. Random paths reduce guessing, not access by link holders; withdrawing a batch requires deleting its COS objects and purging its CDN directory. +Distribute each test batch through its complete download links. Installed test clients retain their batch feed and do not discover a new ID automatically. Format validation cannot establish randomness; use the generator output. Random paths reduce guessing, not access by link holders; withdrawing a batch requires deleting its COS objects and purging its CDN directory. Configure the update origin and selected COS bucket, SecretId, and SecretKey in the target dotenv file, then package and upload the same target: diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index e9367d5708..48fc783501 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -158,6 +158,8 @@ pwsh -NoProfile -File apps/desktop/scripts/smoke-windows.ps1 -Makensis $Makensis Windows 安装器先将新版本解压到安装目录旁边,再退出旧应用并通过同卷目录改名完成替换。同路径升级在替换成功前保留旧目录;解压失败时旧版不变,替换失败时尝试恢复旧目录。安装器在启动前清理旧版备份。强制结束安装器或断电可能留下 `.new-*` 或 `.old-*` 目录;不同安装位置或安装范围迁移仍使用 electron-builder 的旧卸载器流程。 + + ### 上传更新 test 与 production 的 `upload:*` 上传在发布前置检查通过后,分别保留新的 `.desktop-build/upload-records/--*` 目录。`plan.json` 记录目标、版本、每个文件的大小/SHA-512 和发布的 YAML 字节;刷盘的 `events.jsonl` 记录 PUT 意图及可用的响应状态/请求 ID;`result.json` 记录完成结果或最后失败阶段。缺少最终结果表示中断或存储不可用,不表示成功。不记录凭据值、认证头或原始 SDK 错误。审计写入失败即停止后续 PUT。每个对象都以一次流式腾讯 COS PUT 上传,并携带显式长度与 Content-MD5;COS SDK 仅在请求体不是流时才会重发请求,上传器自身也不重试。保留部分记录,检查远端状态后再执行下一次操作:超时或回执写入失败不能证明对象未存储。这些记录仅在本地,不防篡改,也不会自动备份;每次发布应将它们与构建证据一同归档到受控存储。公网 CDN 回读仍是单独的发布验收,上传结果明确标记为 `not-performed`。 @@ -173,13 +175,13 @@ Windows 操作人员可以在仓库外保存 CLIXML 对象,其中 `SecretId` | `test` 或未设置 | `DOWNLOAD_TEST_ORIGIN` | `DOWNLOAD_TEST_COS_BUCKET` | `DOWNLOAD_TEST_COS_SECRET_ID`、`DOWNLOAD_TEST_COS_SECRET_KEY` | | `production` | `https://download.deepseek.com` | `DOWNLOAD_PROD_COS_BUCKET` | `DOWNLOAD_PROD_COS_SECRET_ID`、`DOWNLOAD_PROD_COS_SECRET_KEY` | -每个测试发布批次用下方命令生成新 ID,将输出填入 `.env.macos` 或 `.env.windows` 的 `DOWNLOAD_TEST_RELEASE_ID`。这两个被 Git 忽略的平台文件管理该值,shell 变量不能覆盖它,dotenv 值也不会进行 shell 展开。打包、上传和重试必须沿用同一个 ID;上传会拒绝更新 URL 不一致的完成记录。生产环境不使用该字段。 +每个测试发布批次用下方命令生成新 ID,将输出填入 `.env.macos` 或 `.env.windows` 的 `DOWNLOAD_TEST_RELEASE_ID`。这两个被 Git 忽略的平台文件管理该值,shell 变量不能覆盖它,dotenv 值也不会进行 shell 展开。打包、上传和重试必须沿用同一个 ID;上传会拒绝更新 URL 不一致的完成记录。需要验证跨版本升级时,后续版本沿用已安装客户端的 ID。生产环境不使用该字段。 ```sh -node --input-type=module -e 'import { randomBytes } from "node:crypto"; console.log(randomBytes(16).toString("hex"))' +node --input-type=module -e "import { randomBytes } from 'node:crypto'; console.log(randomBytes(16).toString('hex'))" ``` -通过完整下载链接分发每个测试批次。已安装的测试客户端保留当前批次的清单地址,不会自动发现新 ID。随机路径降低被猜中的概率,不限制持有链接者访问;撤下批次需要删除其 COS 对象并清除对应 CDN 目录缓存。 +通过完整下载链接分发每个测试批次。已安装的测试客户端保留当前批次的清单地址,不会自动发现新 ID。格式校验无法判断随机性,请使用生成器的输出。随机路径降低被猜中的概率,不限制持有链接者访问;撤下批次需要删除其 COS 对象并清除对应 CDN 目录缓存。 在目标 `.env` 中配置更新地址与所选 COS bucket、SecretId、SecretKey,再打包并上传同一个目标: diff --git a/apps/desktop/tests/installed-update/README.i18n.yaml b/apps/desktop/tests/installed-update/README.i18n.yaml index 8ea70c5cbc..036b9a3a62 100644 --- a/apps/desktop/tests/installed-update/README.i18n.yaml +++ b/apps/desktop/tests/installed-update/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write apps/desktop/tests/installed-update/README.md -README.md: 139a80246d6539898cc870129fe55ad726b2673d -README.zh.md: 2b140cceb37ac104c1984c35322da0814ac365b7 +README.md: b847960862931a8c7ef769908d046cfb0f893d41 +README.zh.md: ac2bed4e2a0304f0362c36504128ff17fc5ba693 diff --git a/apps/desktop/tests/installed-update/README.md b/apps/desktop/tests/installed-update/README.md index 139a80246d..b847960862 100644 --- a/apps/desktop/tests/installed-update/README.md +++ b/apps/desktop/tests/installed-update/README.md @@ -44,7 +44,7 @@ Package both files from the generated `bootstrap` directory beside `lib/`, and s The `application` command copies built main/preload modules, renderer files, and the prepared bootstrap into `application/files`, with SHA-256 values in `application/result.json`. It does not copy the app's root `.env.windows` or freeze `node_modules` and build tools. The [qualification builder configuration](../../scripts/installed-update-builder.ts) verifies this inventory and the selected private runtime, selects the shared frozen files and isolated package metadata, and preserves ordinary installer and signing hooks. Its tests substitute the signer and pass the pinned builder's configuration validator; they do not produce an installer. A separately authorized supervised build must still record dependency/tool inputs and verify final package contents and signatures. -The [packaging entry](../../scripts/package-installed-update.ts) defaults to checks. A retained signing interlock rejects before credentials are loaded; it never clears that interlock. With no interlock, checks load `.env.windows`, validate prepared inputs, and launch no child. Run this from the repository root with one exact version: +The [packaging entry](../../scripts/package-installed-update.ts) defaults to checks. A retained signing interlock rejects before credentials are loaded; it never clears that interlock. With no interlock, checks load `.env.windows`, validate prepared inputs, and launch no child. The shared builder requires a valid `DOWNLOAD_TEST_RELEASE_ID` from the [test release settings](../../README.md#upload-updates); qualification still publishes through the manifest’s separate `qualification/` paths. Run this from the repository root with one exact version: ```powershell node --import tsx apps/desktop/scripts/package-installed-update.ts "" 0.1.6-alpha.1.20260916.1 --check diff --git a/apps/desktop/tests/installed-update/README.zh.md b/apps/desktop/tests/installed-update/README.zh.md index 2b140cceb3..ac2bed4e2a 100644 --- a/apps/desktop/tests/installed-update/README.zh.md +++ b/apps/desktop/tests/installed-update/README.zh.md @@ -44,7 +44,7 @@ node --import tsx apps/desktop/scripts/prepare-installed-update.ts application " `application` 命令将已构建的主程序/预加载模块、界面文件和准备好的启动入口复制到 `application/files`,并在 `application/result.json` 中记录 SHA-256。它不复制应用根目录的 `.env.windows`,也不冻结 `node_modules` 与构建工具。[验收打包配置](../../scripts/installed-update-builder.ts)校验该清单与选定的独立运行时,选用共享冻结文件和隔离包元数据,并保留常规安装器与签名钩子。其测试替换签名器,并通过固定版本构建器的配置校验;测试不生成安装器。另行授权的受监督构建仍须记录依赖/工具输入,并验证最终包内容及签名。 -[打包入口](../../scripts/package-installed-update.ts)默认只检查。保留的签名保护锁会在读取凭据前使其拒绝;入口绝不清除此锁。没有保护锁时,检查会加载 `.env.windows`、校验准备输入,不启动子进程。在仓库根目录使用一个准确版本执行: +[打包入口](../../scripts/package-installed-update.ts)默认只检查。保留的签名保护锁会在读取凭据前使其拒绝;入口绝不清除此锁。没有保护锁时,检查会加载 `.env.windows`、校验准备输入,不启动子进程。共享构建器要求[测试发布配置](../../README.zh.md#upload-updates)中有效的 `DOWNLOAD_TEST_RELEASE_ID`;资格验收仍使用清单中独立的 `qualification/` 路径发布。在仓库根目录使用一个准确版本执行: ```powershell node --import tsx apps/desktop/scripts/package-installed-update.ts "" 0.1.6-alpha.1.20260916.1 --check From e71df56b1a2b6511bc7184a58c6a6142e934bed9 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 14:59:15 +0800 Subject: [PATCH 03/27] feat(workspace): create the default workspace on first send --- ...ession-scope-and-provide-channel.i18n.yaml | 4 +- ...lient-session-scope-and-provide-channel.md | 8 +- ...nt-session-scope-and-provide-channel.zh.md | 8 +- .../2026-09-20-default-workspace.i18n.yaml | 6 + .../feature/2026-09-20-default-workspace.md | 32 ++++ .../2026-09-20-default-workspace.zh.md | 32 ++++ apps/web/tests/default-workspace.e2e.ts | 122 +++++++++++++++ .../default-workspace/failure.expected.md | 6 + apps/web/tests/scaffold.ts | 2 + apps/web/tests/support.ts | 23 +-- apps/web/tsconfig.json | 1 + docs/config-catalog.i18n.yaml | 4 +- docs/config-catalog.md | 19 ++- docs/config-catalog.zh.md | 19 ++- docs/subsystems/workspace.i18n.yaml | 4 +- docs/subsystems/workspace.md | 23 +++ docs/subsystems/workspace.zh.md | 23 +++ .../api/workspace-controller/README.i18n.yaml | 4 +- packages/api/workspace-controller/README.md | 12 ++ .../api/workspace-controller/README.zh.md | 12 ++ .../api/workspace-controller/package.json | 2 + .../workspace-controller/src/client/index.ts | 2 +- .../workspace-controller/src/client/model.ts | 13 ++ .../src/client/service.ts | 15 +- .../src/default-directory.ts | 79 ++++++++++ .../api/workspace-controller/src/index.ts | 53 ++++++- .../api/workspace-controller/src/types.ts | 8 + .../tests/default-directory.host.spec.ts | 48 ++++++ .../tests/model.client.spec.ts | 17 +++ .../tests/remote/workspace.client.ts | 1 + .../tests/transport.client.spec.ts | 5 + .../tests/workspace-controller.host.spec.ts | 48 +++++- .../workspace-controller/tsconfig.host.json | 5 +- .../client/ui-agent-preset/README.i18n.yaml | 4 +- packages/client/ui-agent-preset/README.md | 2 + packages/client/ui-agent-preset/README.zh.md | 2 + .../ui-agent-preset/src/client/index.ts | 8 + .../ui-agent-preset/src/client/seat-store.ts | 13 +- .../tests/apply.client.spec.ts | 33 +++- .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 6 +- packages/client/ui-conversation/README.zh.md | 6 +- .../ui-conversation/src/client/apply.ts | 41 +++-- .../src/client/contract/input.ts | 6 + .../src/client/contract/slots.ts | 13 +- .../ui-conversation/src/client/index.ts | 8 + .../src/client/input/facade.ts | 4 +- .../src/client/input/first-draft.ts | 79 ++++++++++ .../ui-conversation/src/client/locales.ts | 8 + .../client/skeleton/ConversationContent.tsx | 40 +++-- .../src/client/skeleton/ConversationRoot.tsx | 5 +- .../src/client/skeleton/InputBar.tsx | 81 ++++------ .../tests/apply-inject.client.spec.tsx | 52 ++++++- .../tests/assembly-surfaces.client.spec.tsx | 24 ++- .../tests/first-draft.client.spec.ts | 141 +++++++++++++++++ .../tests/input-bar.client.spec.tsx | 1 + .../tests/input-matrix.client.spec.tsx | 1 + .../tests/input-scenarios.client.spec.tsx | 1 + .../tests/skeleton.client.spec.tsx | 16 ++ packages/client/ui-workspace/README.i18n.yaml | 4 +- packages/client/ui-workspace/README.md | 2 + packages/client/ui-workspace/README.zh.md | 2 + .../ui-workspace/src/client/navigation.ts | 33 +++- .../tests/workspaces-service.client.spec.ts | 40 +++++ .../extensions/tool-cordis/src/api-catalog.ts | 16 ++ .../client-runtime/src/workspaces.ts | 15 +- packages/workspace/workspace/README.i18n.yaml | 4 +- packages/workspace/workspace/README.md | 13 +- packages/workspace/workspace/README.zh.md | 13 +- packages/workspace/workspace/src/index.ts | 41 ++++- packages/workspace/workspace/src/spec.ts | 2 + .../workspace/tests/workspace.spec.ts | 144 +++++++++++++++++- pnpm-lock.yaml | 6 + scripts/gen-cordis-catalog.ts | 2 + snapshots/web/default-workspace/snapshot.yml | 9 ++ .../web/default-workspace/ui.expected.md | 26 ++++ tsconfig.host.json | 1 + 77 files changed, 1472 insertions(+), 160 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-09-20-default-workspace.md create mode 100644 .agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md create mode 100644 apps/web/tests/default-workspace.e2e.ts create mode 100644 apps/web/tests/expected/default-workspace/failure.expected.md create mode 100644 packages/api/workspace-controller/src/default-directory.ts create mode 100644 packages/api/workspace-controller/tests/default-directory.host.spec.ts create mode 100644 packages/client/ui-conversation/src/client/input/first-draft.ts create mode 100644 packages/client/ui-conversation/tests/first-draft.client.spec.ts create mode 100644 snapshots/web/default-workspace/snapshot.yml create mode 100644 snapshots/web/default-workspace/ui.expected.md diff --git a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.i18n.yaml index e891710dea..2e242505c5 100644 --- a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.md -2026-07-25-web-client-session-scope-and-provide-channel.md: 990a9b6eef862a7ac4a549358beae7f9081eaa0b -2026-07-25-web-client-session-scope-and-provide-channel.zh.md: 5c90611fab36611766bb407138c4f0c8a6b3a01b +2026-07-25-web-client-session-scope-and-provide-channel.md: e2541836edc18755c2e49d30a10b44d2d3a7bcc3 +2026-07-25-web-client-session-scope-and-provide-channel.zh.md: fd082cc74974a22a69a67cbf657693911aea8f99 diff --git a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.md b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.md index 990a9b6eef..e2541836ed 100644 --- a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.md +++ b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.md @@ -26,8 +26,8 @@ The reference-owned lifetime and Provider targeting now follow [Client Session r Host-side `session.create(workspaceId)` produces Session + Agent + cwd in one piece (an atomic bundle, never split); the client side is the mirror of that birth — the instant a session row enters the list mirror, the client mints its Agent scope (actx + provide + the full input surface mounted): - Session identity is the host's true form from birth: the sessionId arrives via the `session.create` response / the `host/session-added` frame, and every client-side address (the scope tag, slot store keys, RPC addressing) uses that same id. -- The materialization moment = the instant the user picks a Workspace (cwd settled): the client calls `session.create({workspaceId})` on the spot and receives the complete entity. -- "New Session with no workspace picked" is a **pure view state** (a navigation position) corresponding to no session/scope entity; until the pick, the composer is locked whole (no slash, no plain text). +- A manual Workspace pick or successful [first-use default preparation](../feature/2026-09-20-default-workspace.md) establishes cwd before the client calls `session.create({workspaceId})` and receives the complete entity. +- "New Session with no workspace picked" has no Session or scope entity. The composer retains a local text draft; Session-scoped slash commands become available after connection. - A "blank session" is just an ordinary materialized session whose log is still empty; to every Agent-scope plugin on the host (goal/plan/skill/…) it is indistinguishable from any session, so slash/plan are all naturally live. ### Agent scope: the actx is the sole session carrier in the client-side cordis world @@ -95,7 +95,7 @@ Slot scope is the closed set `root | session-maybe | session`: - `session-maybe` inherits the nearest `SessionProvider` binding with ADOPTION identity: an incarnation born Session-less keeps its React instance when that Provider receives its first binding, then remounts when the Provider switches generation or returns to absence. Component-local per-Session state clears when the Provider switches generation. Across a switch, only persisted Store values survive generation retirement; binding-owned sources survive only when another reference keeps that generation alive. With no binding, `sessionId`, the results of `useSession`/`useInput`, and `inputActions` may all be absent. Provider-roster changes rematerialize the mounted binding without changing its identity, while the per-entry adoption bookkeeping lives in the renderer's `SessionMaybeEntry`. - `session` guarantees that `sessionId`, every hook source, and every prop exist; each strict entry's error boundary is keyed by `sessionId`, so switching sessions recreates that entry and its session store. -`conversation` is the resident `session-maybe` shell under its owning `SessionProvider`: `ConversationRoot`, HeroShell, the Workspace picker, the scrollport and composer stack, and the overlay chain's fallback frame retain their React instances across the no-Session → blank-Session switch. Two strict entries fill fixed regions without reparenting that tree: `conversation.session.header` carries breadcrumb/tabs/actions above the scrollport, while `conversation.session` carries the view ring and draft mirror inside it; both share the same Session-scoped chat store. The composer bar (`conversation.composer.bar`) is itself `session-maybe`: with no Session its machine faces and message actions are inert, while the whole dashed card opens the existing Workspace picker by pointer and its read-only textarea does the same through Enter or Space. The same instance — textarea included — goes live when a binding appears; the remaining input slots stay strict `session` and dispatch nothing until then. The blank → engaging/active transition never rebuilds the InputBar on a phase flip. +`conversation` is the resident `session-maybe` shell under its owning `SessionProvider`: `ConversationRoot`, HeroShell, the Workspace picker, the scrollport and composer stack, and the overlay chain's fallback frame retain their React instances across the no-Session → blank-Session switch. Two strict entries fill fixed regions without reparenting that tree: `conversation.session.header` carries breadcrumb/tabs/actions above the scrollport, while `conversation.session` carries the view ring and draft mirror inside it; both share the same Session-scoped chat store. The composer bar (`conversation.composer.bar`) is itself `session-maybe`: before a Session exists, its injected editor retains the first-use text draft; after connection, the same InputBar instance receives the retained Session's input. The remaining input slots stay strict `session` and dispatch nothing until then. The blank → engaging/active transition never rebuilds the InputBar on a phase flip. Blank Sessions retain the header's leading and corner slots so navigation controls, including the right-sidebar opener, are available before the first message. Title, actions, utilities, and View tabs remain hidden in the blank phase. The header still requires a selected Session; the Files and Terminal entries use that Session's workspace and execution services without requiring a recorded Turn. @@ -136,5 +136,5 @@ Blank Sessions retain the header's leading and corner slots so navigation contro - Plugins gain session context isomorphic to the host's: per-session state hangs on the actx and mounts/tears down in one piece with the scope fiber, making leaks structurally impossible; two-session isolation is structurally guaranteed by the scope filter. - The client object layer converges to a wire mirror: session identity, lifecycle, and capability adjudication all defer to the host entity — the input system (the next layer) always faces a session with a real Agent, and providers like slash/skill uniformly address by sessionId directly. - Blank-session governance takes zero dedicated mechanisms: state rides one derived bit, visibility rides the unified list projection (only the current blank shows, as `New Session`), reuse acquires the persisted writer, and the ordinary ceiling rides same-Workspace reuse. -- The cost: the id→ctx handoff discipline and provide's Concurrent discipline are conventions rather than type-enforced, pinned by review and tests. The single state axis still withholds machine faces until a Session exists; the [resident conversation shell](../../../../packages/client/ui-conversation/README.md) routes activation to the Workspace picker during that interval. +- The cost: the id→ctx handoff discipline and provide's Concurrent discipline are conventions rather than type-enforced, pinned by review and tests. Session-scoped input remains unavailable until a Session exists; the [resident conversation shell](../../../../packages/client/ui-conversation/README.md) owns the local first-use draft during that interval. - Known gaps: approval/question recovery across prune (TODO); model selection returns in live-mutation shape (the host `selectModel` trio is ready-made, its client consumer not yet built). diff --git a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md index 5c90611fab..fd082cc749 100644 --- a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md @@ -26,8 +26,8 @@ web client 只有一张全局会话面:slot 全部从根上下文渲染,插 host 侧 `session.create(workspaceId)` 一体产出 Session + Agent + cwd(作为不可拆分的原子整体);client 侧就是这次出生的镜像——会话行进入 list mirror 的瞬间,client 为它铸 Agent scope(actx + provide + 输入面全套挂上): - 会话身份自出生即为 host 真身:sessionId 由 `session.create` 响应 / `host/session-added` 帧带来,client 侧一切寻址(scope tag、slot store 键、RPC 地址)用的都是同一个 id。 -- 实体化时点 = 用户选定 Workspace(cwd 确定)的瞬间:client 当场调 `session.create({workspaceId})`,拿到完整实体。 -- 「New Session 且未选 workspace」是**纯视图态**(一个导航位置),不对应任何会话/scope 实体;选定之前 composer 整体锁死(无 slash、无纯文本)。 +- 手动选择 Workspace 或成功[准备首次使用默认工作区](../feature/2026-09-20-default-workspace.zh.md)先确定 cwd,client 随后调用 `session.create({workspaceId})` 并取得完整实体。 +- 「New Session 且未选 workspace」没有 Session 或 scope 实体。Composer 保留本地文本草稿;连接后才提供 Session scope 的 slash 命令。 - 「空会话」就是一个日志还空着的普通实体化会话;对 host 上所有 Agent-scope 插件(goal/plan/skill(技能)/…)它与任何会话无异,slash/plan 天然全活。 ### Agent scope:actx 是 client 侧 cordis 世界的唯一会话载体 @@ -95,7 +95,7 @@ slot scope 是闭集 `root | session-maybe | session`: - `session-maybe` 以**收养(adoption)身份语义**继承最近 `SessionProvider` 的 binding:空态出生的化身在该 Provider 第一次收到 binding 时保持 React 实例,此后 Provider 切换 generation 或回到空态时重挂。Provider 切换 generation 时,组件本地的逐 Session 状态会清零。切换过程中,只有持久化 Store 值能活过 generation 退休;只有另一份 reference 保活该 generation 时,binding 自有 source 才能保留。无 binding 时,`sessionId`、`useSession`/`useInput` 的结果与 `inputActions` 均可缺省。Provider roster 变化会重新物化已挂载 binding,但不改变其 identity;逐 entry 的收养记账住在 renderer 的 `SessionMaybeEntry`。 - `session` 保证 `sessionId`、所有钩子 source 与 props 均存在;每个严格 entry 的错误边界以 `sessionId` 为 key,切换会话会重建该 entry 及其会话 store。 -`conversation` 是其 owner `SessionProvider` 下的 `session-maybe` 常驻外壳:`ConversationRoot`、HeroShell、Workspace picker、scrollport 与 composer stack,以及 overlay chain 的 fallback 外框,在无 Session → blank Session 的切换中保持 React 实例。两个严格 session entry 只填入固定区域,不改变该树的父级:`conversation.session.header` 在 scrollport 上方承载 breadcrumb/tab/action,`conversation.session` 在其内部承载 view ring 与 draft mirror;二者共享同一个 Session scope chat store。composer bar(`conversation.composer.bar`)本身即为 `session-maybe`:无 Session 时,其 machine faces 和消息动作保持惰性,整张虚线卡片可经指针打开现有 Workspace picker,只读 textarea 也可通过 Enter 或 Space 打开。binding 出现后同一实例(含 textarea)转为 live;其余输入 slot 保持严格 `session`,在此之前不派发任何内容。blank → engaging/active 的 InputBar 不因 phase 翻转而重建。 +`conversation` 是其 owner `SessionProvider` 下的 `session-maybe` 常驻外壳:`ConversationRoot`、HeroShell、Workspace picker、scrollport 与 composer stack,以及 overlay chain 的 fallback 外框,在无 Session → blank Session 的切换中保持 React 实例。两个严格 session entry 只填入固定区域,不改变该树的父级:`conversation.session.header` 在 scrollport 上方承载 breadcrumb/tab/action,`conversation.session` 在其内部承载 view ring 与 draft mirror;二者共享同一个 Session scope chat store。composer bar(`conversation.composer.bar`)本身即为 `session-maybe`:Session 存在前,注入的编辑器保存首次使用文本草稿;连接后,同一 InputBar 实例接收已持有 Session 的输入。其余输入 slot 保持严格 `session`,在此之前不派发任何内容。blank → engaging/active 的 InputBar 不因 phase 翻转而重建。 blank Session 保留 header 的 leading 与 corner slot,让右侧栏展开入口等导航控件在首条消息之前即可使用。标题、actions、utilities 和 View tabs 在 blank phase 中继续隐藏。header 仍要求已选中的 Session;Files 与 Terminal 入口使用该 Session 的工作区和执行服务,无需已有 Turn 记录。 @@ -136,5 +136,5 @@ blank Session 保留 header 的 leading 与 corner slot,让右侧栏展开入 - 插件获得与 host 同构的会话上下文:逐会话状态挂 actx、随 scope fiber 一次拆装,泄漏结构性不可能;双会话隔离由 scope filter 结构性保证。 - client 对象层收敛为 wire 镜像:会话身份、生命周期、能力判别全部以 host 实体为准——输入体系(下一层)面对的永远是「有真 Agent 的会话」,slash/skill 等提供方一律以 sessionId 直接寻址。 - 空会话治理零专用机制:状态靠一个派生位,可见性靠统一列表投影(仅 current blank 以 `New Session` 展示),复用时获取持久化写锁,常规上限靠同 Workspace 复用。 -- 代价:id→ctx 换乘纪律、provide 的 Concurrent 纪律都是约定而非类型强制,靠 review 与测试钉住。单一状态轴仍会在 Session 存在前隐藏 machine face;这段时间内,[常驻会话壳](../../../../packages/client/ui-conversation/README.zh.md)会把激活操作转到 Workspace picker。 +- 代价:id→ctx 换乘纪律、provide 的 Concurrent 纪律都是约定而非类型强制,靠 review 与测试钉住。Session 存在前,其 scope 输入仍不可用;这段时间内,[常驻会话壳](../../../../packages/client/ui-conversation/README.zh.md)负责本地首次使用草稿。 - 已知欠账:approval/question 跨 prune 恢复(TODO);模型选择以 live-mutation 形状回归(host `selectModel` 三件套现成,其 client 消费方尚未构建)。 diff --git a/.agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml b/.agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml new file mode 100644 index 0000000000..cdb2673df8 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-20-default-workspace.md +2026-09-20-default-workspace.md: d2a32d47a407dcf211c1cad8bb98f29847a77a3b +2026-09-20-default-workspace.zh.md: 6b0ec542da6e9e4fe76fb56b6562edea9e5777f4 diff --git a/.agents/notes/implemented/feature/2026-09-20-default-workspace.md b/.agents/notes/implemented/feature/2026-09-20-default-workspace.md new file mode 100644 index 0000000000..d2a32d47a4 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-20-default-workspace.md @@ -0,0 +1,32 @@ +# Agent Note: First-use default Workspace + +Status: implemented + +English | [中文](2026-09-20-default-workspace.zh.md) + +## Problem + +A new installation requires a directory choice before the user can send a first message. Removing that prerequisite must preserve the Session's fixed working directory and must not treat hidden or archived history as a new installation. + +## Decision + +The conversation shell retains an unsent local text draft without creating a Session. Its first send asks the Host to prepare a default Workspace, then connects a real Session and submits through the ordinary composer pipeline. The first-use draft awaits staged mode selection before automatic submission. This partially supersedes the locked no-Session composer in [Session scope and provisioning](../architecture/2026-07-25-web-client-session-scope-and-provide-channel.md); that note still owns blank-Session reuse and provisioning rationale. + +The [Workspace registry](../../../../packages/workspace/workspace/README.md#first-use-workspace) owns eligibility and directory preparation. All live Sessions, persisted headers, and archived identities count, including entries absent from the sidebar. The operation shares the registry mutation queue and rechecks Session history after directory preparation because Sessions can start independently. + +The Client resolves the initial directory name and title from its language when sending. The Host controller resolves the Documents location; the registry receives a directory resolver with no locale dependency. The resolver runs inside the mutation queue only for eligible creation, so repeated requests reuse the durable Workspace without another OS lookup. A durable Workspace id records successful initialization independently of that name. Renaming, changing language, restarting, or deleting the registration cannot initialize another default. The marker commits with the registration, so a failed registration can retry. Directory contents remain subject to the existing [metadata-only deletion policy](2026-07-27-workspace-registration-deletion.md). + +Creation failure preserves the draft and offers the existing folder picker. A successful registration survives Session creation or prompt failure. Picking a folder after failure transfers the text without sending it; a later send remains the user's action. + +## Alternatives considered + +- Creating on application startup would write directories for users who never send a message. +- Inferring first use from visible sidebar rows would ignore archived, hidden, and cwd-less Sessions. +- Using the localized path as the initialization marker would allow language changes or deletion to create another default. +- Changing a Session's cwd after creation would change the meaning of its recorded tools and attachments. + +## Consequences + +First-use typing has no Host Session or filesystem effects. Preparation remains a Host responsibility for both Desktop and remote Web clients, so remote users use the Host account's Documents location. Unavailable Documents lookup fails with the same folder-selection recovery as directory creation failure. + +The feature preserves [reference-owned Client Session lifetimes](../architecture/2026-09-15-client-session-references.md) and requires no agent-loop or Session-event change. Registry and client tests cover retries, hidden history, concurrency, and draft recovery; the [browser scenario](../../../../apps/web/tests/default-workspace.e2e.ts) verifies the assembled first-send and picker paths with an isolated Documents directory and recorded Session replay. diff --git a/.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md b/.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md new file mode 100644 index 0000000000..6b0ec542da --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md @@ -0,0 +1,32 @@ +# Agent Note: 首次使用默认 Workspace + +Status: implemented + +[English](2026-09-20-default-workspace.md) | 中文 + +## Problem + +新安装的应用要求用户先选目录才能发送第一条消息。去掉这一步前置操作时,必须保留 Session 的固定工作目录,也不能把隐藏或已归档的历史误判为新安装。 + +## Decision + +会话外壳保存未发送的本地文本草稿,不创建 Session。首次发送请求 Host 准备默认 Workspace,随后连接真实 Session,并通过常规 composer 流程提交。首次使用的草稿会在自动提交前等待暂存的模式选择完成。这部分取代[Session scope 与供给通道](../architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md)中无 Session 时锁定 composer 的决策;该记录仍负责 blank Session 复用与供给通道的理由。 + +[Workspace registry](../../../../packages/workspace/workspace/README.zh.md#first-use-workspace)负责资格判断和目录准备。所有 live Session、持久化 header 和已归档身份都计入判断,包括侧栏中不可见的条目。操作共用 registry 修改队列,并在目录准备后重新检查 Session 历史,因为 Session 可以独立启动。 + +Client 在发送时按其语言解析初始目录名和标题。Host 控制器解析 Documents 位置;注册表接收不依赖 locale 的目录解析器。解析器仅在允许创建时于变更队列内运行,因此重复请求直接复用持久化的 Workspace,无需再次查询操作系统目录。持久化 Workspace id 独立于名称记录初始化成功。改名、切换语言、重启或删除登记均不能再次初始化默认工作区。标记与登记一起提交,因此登记失败可以重试。目录内容仍遵循已有的[仅删除元数据策略](2026-07-27-workspace-registration-deletion.zh.md)。 + +创建失败时保留草稿,并提供现有文件夹选择器。成功的登记会在 Session 创建或提示词发送失败后保留。失败后选择文件夹只转移文本,不发送;随后发送仍由用户操作。 + +## Alternatives considered + +- 在应用启动时创建,会为从未发送消息的用户写入目录。 +- 根据侧栏可见行推断首次使用,会忽略已归档、隐藏和无 cwd 的 Session。 +- 将本地化路径作为初始化标记,会允许切换语言或删除后再次创建默认工作区。 +- 在 Session 创建后更改 cwd,会改变其已记录工具和附件的含义。 + +## Consequences + +首次使用时输入文本不会产生 Host Session 或文件系统副作用。Desktop 和远程 Web 客户端均由 Host 准备目录,因此远程用户使用 Host 账户的 Documents 位置。Documents 查询不可用时,采用与目录创建失败相同的文件夹选择恢复路径。 + +该功能保留[由引用持有的 Client Session 生命周期](../architecture/2026-09-15-client-session-references.zh.md),无需修改 agent-loop 或 Session 事件。Registry 和客户端测试覆盖重试、隐藏历史、并发及草稿恢复;[浏览器场景](../../../../apps/web/tests/default-workspace.e2e.ts)通过隔离的 Documents 目录和已录制 Session 回放验证完整装配下的首次发送与选择器路径。 diff --git a/apps/web/tests/default-workspace.e2e.ts b/apps/web/tests/default-workspace.e2e.ts new file mode 100644 index 0000000000..00bec9de3c --- /dev/null +++ b/apps/web/tests/default-workspace.e2e.ts @@ -0,0 +1,122 @@ +/** First-use messages prepare a durable Workspace through the shipped Web composition. */ +import { mkdir, readFile, stat, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { chromium } from 'playwright' +import { describe, expect, it } from 'vitest' +import { + captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, launchWebScaffold, + selectedSessionFixture, watchConsole, webSnapshotMode, +} from './scaffold.ts' +import { newEnglishPage, saveFailureShot } from './support.ts' + +const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/fresh-round-trip/session.v3.jsonl', import.meta.url)) +const EXPECTED = fileURLToPath(new URL('../../../snapshots/web/default-workspace/ui.expected.md', import.meta.url)) +const FAILURE_EXPECTED = fileURLToPath(new URL('./expected/default-workspace/failure.expected.md', import.meta.url)) +const MODE = webSnapshotMode() + +describe.skipIf(MODE === 'record')('web e2e: default Workspace', () => { + it('sends the first draft in a newly selected default Workspace and keeps its identity across reload', async () => { + const fixture = await selectedSessionFixture(FIXTURE) + const scaffold = await launchWebScaffold({ + replayFixture: fixture, + // The shared recording remains read-only; replay compares the complete persisted Session. + compareReplaySession: MODE === 'replay', + paceMs: 5, + }) + try { + const browser = await chromium.launch() + try { + const page = await newEnglishPage(browser) + const tripwire = watchConsole(page) + try { + await page.goto(scaffold.authenticatedUrl) + const input = page.locator('[data-composer-input][contenteditable="true"]').first() + await input.waitFor() + const prompt = fixtureUserPrompts(await readFile(fixture, 'utf8'))[0]! + await input.fill(prompt) + expect(scaffold.ctx.workspaceRegistry.list()).toEqual([]) + expect(scaffold.ctx.sessions.list()).toEqual([]) + const settled = scaffold.whenTurnSettled() + await input.press('Enter') + const sessionId = await settled + const workspace = scaffold.ctx.workspaceRegistry.list()[0]! + expect(workspace.title).toBe('Default workspace') + expect(workspace.path).toBe(join(scaffold.workspaceCwd, 'Documents', 'deepseek-harness', 'Default workspace')) + expect((await stat(workspace.path)).isDirectory()).toBe(true) + expect(workspace.sessionIds).toContain(sessionId) + expect(scaffold.ctx.sessions.get(sessionId)?.header.cwd).toBe(workspace.path) + await page.getByText('DONE', { exact: true }).waitFor() + await compareOrRefreshGolden(EXPECTED, await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd), MODE) + await page.reload() + await page.getByText('DONE', { exact: true }).waitFor() + expect(scaffold.ctx.workspaceRegistry.list().map(item => item.id)).toEqual([workspace.id]) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + } catch (error) { + await saveFailureShot(page, 'web-e2e-default-workspace') + throw error + } + } finally { + await browser.close() + } + } finally { + await scaffold.close() + } + }) + + it('keeps the draft on a directory conflict and opens the composed folder picker for recovery', async () => { + const scaffold = await launchWebScaffold() + try { + const parent = join(scaffold.workspaceCwd, 'Documents', 'deepseek-harness') + await mkdir(parent, { recursive: true }) + await writeFile(join(parent, '默认工作区'), 'occupied') + const chosen = join(scaffold.workspaceCwd, 'chosen') + await mkdir(chosen) + const browser = await chromium.launch() + try { + const page = await browser.newPage({ locale: 'zh-CN', timezoneId: 'Asia/Shanghai' }) + const tripwire = watchConsole(page) + try { + await page.goto(scaffold.authenticatedUrl) + const input = page.locator('[data-composer-input][contenteditable="true"]').first() + await input.fill('保留这条消息') + await input.press('Enter') + const modal = page.getByRole('dialog', { name: '无法创建默认工作区' }) + await modal.waitFor() + await expect.poll(() => input.textContent()).toBe('保留这条消息') + expect(scaffold.ctx.workspaceRegistry.list()).toEqual([]) + expect(scaffold.ctx.sessions.list()).toEqual([]) + await compareOrRefreshGolden(FAILURE_EXPECTED, await modal.ariaSnapshot(), MODE) + await modal.getByRole('button', { name: '取消', exact: true }).click() + expect(await input.textContent()).toBe('保留这条消息') + await input.press('Enter') + await modal.getByRole('button', { name: '选择文件夹', exact: true }).click() + const picker = page.getByRole('dialog', { name: '选择工作区目录' }) + await picker.waitFor() + await picker.getByRole('button', { name: '编辑路径', exact: true }).click() + await picker.getByRole('textbox', { name: '编辑路径' }).fill(chosen) + await page.keyboard.press('Enter') + await picker.getByRole('button', { name: '打开', exact: true }).click() + await picker.waitFor({ state: 'hidden' }) + await expect.poll(() => scaffold.ctx.workspaceRegistry.list().length).toBe(1) + await page.getByRole('treeitem', { name: '新会话', exact: true }).waitFor() + await expect.poll(() => input.textContent()).toBe('保留这条消息') + expect(scaffold.ctx.workspaceRegistry.list()[0]?.path).toBe(chosen) + expect(scaffold.ctx.sessions.list()).toHaveLength(1) + expect(scaffold.ctx.sessions.list().every(session => + session.snapshotEvents().every(event => event.type !== 'user/message'))).toBe(true) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + } catch (error) { + await saveFailureShot(page, 'web-e2e-default-workspace-failure') + throw error + } + } finally { + await browser.close() + } + } finally { + await scaffold.close() + } + }) +}) diff --git a/apps/web/tests/expected/default-workspace/failure.expected.md b/apps/web/tests/expected/default-workspace/failure.expected.md new file mode 100644 index 0000000000..6944d1cf14 --- /dev/null +++ b/apps/web/tests/expected/default-workspace/failure.expected.md @@ -0,0 +1,6 @@ +- dialog "无法创建默认工作区": + - heading "无法创建默认工作区" [level=2] + - button "关闭" + - text: 请选择一个文件夹后重试 + - button "取消" + - button "选择文件夹" diff --git a/apps/web/tests/scaffold.ts b/apps/web/tests/scaffold.ts index e7249a0b67..75371e73b2 100644 --- a/apps/web/tests/scaffold.ts +++ b/apps/web/tests/scaffold.ts @@ -600,6 +600,8 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise { } /** - * Drive the hero's workspace picker through the composed directory dialog - * until the live composer unlocks. A fresh world has no Workspace, so the boot - * lands in the Workspace-trigger view state (startup auto-selection has nothing to - * select); every scenario that types into the composer must connect one - * first. With nothing to list, activating the composer surface raises the dialog directly — - * adding a workspace is the picker's only entry. The directory is staged here - * and adopted through the path editor, which is idempotent across the repeated - * connects a scenario may make; creating a folder from inside the dialog (the - * product's other half of the same route) is covered by - * workspace-management.e2e.ts. The default name 'workspace' keeps the session - * header cwd at /workspace, the materialization proof several scenarios - * assert. + * Select a staged directory through the hero's composed Workspace picker. + * The default name keeps the Session cwd at /workspace for scenarios + * that require a specific directory instead of automatic first-use preparation. * @param page - the page under test. * @param root - host directory the workspace folder is staged in (the scaffold's `workspaceCwd`). * @param name - folder name staged and adopted as the workspace. */ export async function connectFreshWorkspace(page: Page, root: string, name = 'workspace'): Promise { mkdirSync(join(root, name), { recursive: true }) - await page.getByRole('textbox', { name: 'Choose workspace' }).click() + await page.getByRole('button', { name: 'Choose workspace', exact: true }).click() const dialog = page.getByRole('dialog', { name: 'Select Workspace Directory' }) await dialog.waitFor({ timeout: 10_000 }) await dialog.getByRole('button', { name: 'Edit path' }).click() @@ -131,8 +122,7 @@ export async function connectFreshWorkspace(page: Page, root: string, name = 'wo await pathInput.fill(join(root, name)) await pathInput.press('Enter') await dialog.getByRole('button', { name: 'Open', exact: true }).click() - // The pick connected the workspace: the blank session's live composer - // replaces the locked placeholder and enables. + await page.getByRole('treeitem', { name: 'New Session', exact: true }).waitFor({ timeout: 15_000 }) await page.locator('[data-composer-input][contenteditable="true"][data-placeholder="Describe what you want to build, / commands, @ files or sessions"]') .waitFor({ timeout: 15_000 }) } @@ -148,7 +138,7 @@ export async function connectFreshWorkspace(page: Page, root: string, name = 'wo */ export async function connectFreshWorkspaceZh(page: Page, root: string, name = 'workspace'): Promise { mkdirSync(join(root, name), { recursive: true }) - await page.getByRole('textbox', { name: '选择工作区' }).click() + await page.getByRole('button', { name: '选择工作区', exact: true }).click() const dialog = page.getByRole('dialog', { name: '选择工作区目录' }) await dialog.waitFor({ timeout: 10_000 }) await dialog.getByRole('button', { name: '编辑路径' }).click() @@ -156,6 +146,7 @@ export async function connectFreshWorkspaceZh(page: Page, root: string, name = ' await pathInput.fill(join(root, name)) await pathInput.press('Enter') await dialog.getByRole('button', { name: '打开', exact: true }).click() + await page.getByRole('treeitem', { name: '新会话', exact: true }).waitFor({ timeout: 15_000 }) await page.locator('[data-composer-input][contenteditable="true"][data-placeholder="描述你想要构建的内容, / 调用指令, @ 文件或对话"]') .waitFor({ timeout: 15_000 }) } diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 4508e03def..8560d4f99e 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -63,6 +63,7 @@ "tests/deepseek-messages-chat.e2e.ts", "tests/models-settings-recovery.e2e.ts", "tests/default-model.e2e.ts", + "tests/default-workspace.e2e.ts", "tests/github-ready-review.e2e.ts", "tests/streaming-fence-highlight.e2e.ts", "tests/declared-reasoning.e2e.ts", diff --git a/docs/config-catalog.i18n.yaml b/docs/config-catalog.i18n.yaml index 106e1545fb..4274817f94 100644 --- a/docs/config-catalog.i18n.yaml +++ b/docs/config-catalog.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/config-catalog.md -config-catalog.md: dad6b57ae0712e04ad16729b4067c541f83c68d6 -config-catalog.zh.md: 4ba0378810f3db4797c0d41fa5230f7069438b3f +config-catalog.md: c3dabe13807ef3ec2db7d861fdc93f9016260bc7 +config-catalog.zh.md: bd3b7e4dbc64627b6b9904360fcfb13f7f3da43e diff --git a/docs/config-catalog.md b/docs/config-catalog.md index dad6b57ae0..c3dabe1380 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -274,6 +274,24 @@ export interface Config { Source: [`packages/api/terminal-controller/src/index.ts:26`](../packages/api/terminal-controller/src/index.ts) + + +## `@deepseek-ai/dsh-api-workspace-controller` + +Requires: `typert` · `workspaceRegistry` + +```ts config-catalog +/** First-use directory policy for the Host account. */ +export interface Config { + /** Override the system Documents directory with a fully qualified path. */ + documentsDirectory?: string + /** Maximum duration of the operating system's Documents lookup. */ + documentsLookupTimeoutMs?: number +} +``` + +Source: [`packages/api/workspace-controller/src/index.ts:34`](../packages/api/workspace-controller/src/index.ts) + ## `@deepseek-ai/dsh-api-workspace-files` @@ -3783,7 +3801,6 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co - `@deepseek-ai/dsh-acp-app` — requires `cmdlineArgs` ([`packages/bundle/acp-app/src/index.ts`](../packages/bundle/acp-app/src/index.ts)) - `@deepseek-ai/dsh-agent` ([`packages/core/agent/src/index.ts`](../packages/core/agent/src/index.ts)) - `@deepseek-ai/dsh-api-remotes` — requires `typertGateway` ([`packages/api/remotes/src/index.ts`](../packages/api/remotes/src/index.ts)) -- `@deepseek-ai/dsh-api-workspace-controller` — requires `typert` · `workspaceRegistry` ([`packages/api/workspace-controller/src/index.ts`](../packages/api/workspace-controller/src/index.ts)) - `@deepseek-ai/dsh-authorization` — requires `credentials` ([`packages/credentials/authorization/src/index.ts`](../packages/credentials/authorization/src/index.ts)) - `@deepseek-ai/dsh-browser-use` ([`packages/browser-use/browser-use/src/index.ts`](../packages/browser-use/browser-use/src/index.ts)) - `@deepseek-ai/dsh-client-file-upload` — requires `agents` · `attachments` · `commands` · `connection` ([`packages/client/file-upload/src/index.ts`](../packages/client/file-upload/src/index.ts)) diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 4ba0378810..bd3b7e4dbc 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -276,6 +276,24 @@ export interface Config { 来源: [`packages/api/terminal-controller/src/index.ts:26`](../packages/api/terminal-controller/src/index.ts) + + +## `@deepseek-ai/dsh-api-workspace-controller` + +需要:`typert` · `workspaceRegistry` + +```ts config-catalog +/** First-use directory policy for the Host account. */ +export interface Config { + /** Override the system Documents directory with a fully qualified path. */ + documentsDirectory?: string + /** Maximum duration of the operating system's Documents lookup. */ + documentsLookupTimeoutMs?: number +} +``` + +源码:[`packages/api/workspace-controller/src/index.ts:34`](../packages/api/workspace-controller/src/index.ts) + ## `@deepseek-ai/dsh-api-workspace-files` @@ -3785,7 +3803,6 @@ export interface Config { - `@deepseek-ai/dsh-acp-app` — 需要 `cmdlineArgs`([`packages/bundle/acp-app/src/index.ts`](../packages/bundle/acp-app/src/index.ts)) - `@deepseek-ai/dsh-agent`([`packages/core/agent/src/index.ts`](../packages/core/agent/src/index.ts)) - `@deepseek-ai/dsh-api-remotes` — 需要 `typertGateway`([`packages/api/remotes/src/index.ts`](../packages/api/remotes/src/index.ts)) -- `@deepseek-ai/dsh-api-workspace-controller` — 需要 `typert` · `workspaceRegistry`([`packages/api/workspace-controller/src/index.ts`](../packages/api/workspace-controller/src/index.ts)) - `@deepseek-ai/dsh-authorization` — 需要 `credentials`([`packages/credentials/authorization/src/index.ts`](../packages/credentials/authorization/src/index.ts)) - `@deepseek-ai/dsh-browser-use` ([`packages/browser-use/browser-use/src/index.ts`](../packages/browser-use/browser-use/src/index.ts)) - `@deepseek-ai/dsh-client-file-upload` — 需要 `agents` · `attachments` · `commands` · `connection`([`packages/client/file-upload/src/index.ts`](../packages/client/file-upload/src/index.ts)) diff --git a/docs/subsystems/workspace.i18n.yaml b/docs/subsystems/workspace.i18n.yaml index db7bb548ef..a7a3e3bb91 100644 --- a/docs/subsystems/workspace.i18n.yaml +++ b/docs/subsystems/workspace.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/workspace.md -workspace.md: 9fe5f2bf4c62ba7d4f878b7b2f34490f43ca0b81 -workspace.zh.md: 63681e1a459c81a327654cfafa1f5cb2f231d6c8 +workspace.md: b68acd965b55df462a0751d0b7e3230c82a62172 +workspace.zh.md: 074f59438eb16a4ffb1423540c3e1868857ae40f diff --git a/docs/subsystems/workspace.md b/docs/subsystems/workspace.md index 9fe5f2bf4c..b68acd965b 100644 --- a/docs/subsystems/workspace.md +++ b/docs/subsystems/workspace.md @@ -121,6 +121,10 @@ Ownership truth is the record's ordered `sessionIds`, never derived from session Sessions get their cwd at create time from whoever creates them, not from this registry — the API gateway resolves a new session's cwd from the chosen workspace's `path` (falling back to an explicit or default cwd), creates the session so the cwd lands in its immutable [`SessionHeader`](persistence.md#sessionheader--metadata-beside-the-log), then calls `attachSession`, which re-validates that stored header cwd against the workspace path. On the first successful start, the registry bootstraps history from persisted headers alone (`id`, `cwd`, `createdAt` — never event bodies), grouping sessions with a valid canonical cwd into per-directory workspaces, newest first; the initialized marker is written last so an interrupted bootstrap resumes safely. The bootstrap is one-time: cwd-less legacy sessions stay Ungrouped, and sessions created afterwards join a workspace only through `attachSession`. +## Default Workspace initialization + +The controller's [transport types](../../packages/api/workspace-controller/src/types.ts) define `WorkspaceInitializeDefaultRequest`: a Client-resolved `directoryName` and initial `title`. The Host resolves the Documents location and asks the registry to initialize once. Locale selection belongs to the Client; the registry accepts a directory resolver and commits the registration with its durable identity. [First-use behavior and configuration](../../packages/api/workspace-controller/README.md#first-use-workspace) describe reuse and failure handling. + ## Session pinning The controller's [transport types](../../packages/api/workspace-controller/src/types.ts) define `WorkspacePinSessionRequest` and `WorkspaceUnpinSessionRequest`, each carrying one `sessionId`. Both operations return `WorkspacePinValue`: the complete `pinnedSessionIds` array of Session ids, most recently pinned first. Pinning requires a known, unarchived Session; unpinning an id that is not pinned succeeds without changing the set. Archiving removes the Session's pin in the same durable write, and unarchiving does not restore it. @@ -301,6 +305,14 @@ Host service backing the generated `ctx.remote.workspace` namespace. */ @Remote('create') create(request: WorkspaceCreateRequest): Promise +/** + * Initialize or reuse the default Workspace before the first user message. + * @param request - initial directory name and title; never rename an existing default. + * @param signal - caller lifetime; cancels native directory lookup. + * @returns the durable Workspace without creating a Session or sending a message. + */ +@Remote('initializeDefault') async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise + /** * Rename one Workspace to a unique non-blank title. * @param request - Workspace identity and proposed title. @@ -466,6 +478,17 @@ Durable workspace registry. Startup waits for `sessionPersistence`, builds one c */ async create(path: string, title?: string): Promise +/** + * Initialize the default Workspace only while both the registry and Session + * history are empty. Repeated requests reuse its durable identity; deleting + * that registration permanently disables automatic creation. + * @param resolveDirectory - resolve the absolute directory and initial title; + * called only for eligible creation, inside the registry mutation queue. + * Missing directories are created recursively before registration. + * @returns the initialized Workspace, or undefined when automatic creation is ineligible. + */ +initializeDefault(resolveDirectory: () => Promise<{ path: string; title: string }>): Promise + /** * Look up a workspace by id. * @param id - Workspace id. diff --git a/docs/subsystems/workspace.zh.md b/docs/subsystems/workspace.zh.md index 63681e1a45..074f59438e 100644 --- a/docs/subsystems/workspace.zh.md +++ b/docs/subsystems/workspace.zh.md @@ -121,6 +121,10 @@ interface Workspace { 会话的 cwd 在创建时由创建者赋予,而不是由本注册表赋予——API 网关从所选工作区的 `path` 解析新会话的 cwd(回退到显式或默认 cwd),先创建会话使 cwd 落入其不可变的 [`SessionHeader`](persistence.zh.md#sessionheader--metadata-beside-the-log),再调用 `attachSession`,后者会把已存储的 header cwd 与工作区路径重新校验一遍。首次成功启动时,注册表仅凭已持久化的 header(`id`、`cwd`、`createdAt`——绝不读事件正文)引导历史:把规范 cwd 有效的会话按目录分组为工作区,最新的排在最前;「已初始化」标记最后写入,因此被中断的引导可以安全续跑。引导只发生这一次:没有 cwd 的历史遗留会话保持 Ungrouped,此后创建的会话只能通过 `attachSession` 加入工作区。 +## 默认工作区初始化 + +控制器的[传输类型](../../packages/api/workspace-controller/src/types.ts)定义了 `WorkspaceInitializeDefaultRequest`,包含 Client 解析出的 `directoryName` 和初始 `title`。Host 解析 Documents 位置,并请求注册表执行一次初始化。语言选择由 Client 负责;注册表接收目录解析器,并将登记与持久化身份一起提交。[首次使用行为与配置](../../packages/api/workspace-controller/README.zh.md#first-use-workspace)说明复用和失败处理。 + ## 会话置顶 控制器的[传输类型](../../packages/api/workspace-controller/src/types.ts)定义了 `WorkspacePinSessionRequest` 和 `WorkspaceUnpinSessionRequest`,两者都携带一个 `sessionId`。两个操作都返回 `WorkspacePinValue`:完整的会话 id 数组 `pinnedSessionIds`,最近置顶的会话排在前面。置顶要求会话已知且未归档;对未置顶的 id 取消置顶会成功,且不改变集合。归档在同一次持久化写入中移除该会话的置顶,取消归档不会恢复置顶。 @@ -301,6 +305,14 @@ Host service backing the generated `ctx.remote.workspace` namespace. */ @Remote('create') create(request: WorkspaceCreateRequest): Promise +/** + * Initialize or reuse the default Workspace before the first user message. + * @param request - initial directory name and title; never rename an existing default. + * @param signal - caller lifetime; cancels native directory lookup. + * @returns the durable Workspace without creating a Session or sending a message. + */ +@Remote('initializeDefault') async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise + /** * Rename one Workspace to a unique non-blank title. * @param request - Workspace identity and proposed title. @@ -466,6 +478,17 @@ Durable workspace registry. Startup waits for `sessionPersistence`, builds one c */ async create(path: string, title?: string): Promise +/** + * Initialize the default Workspace only while both the registry and Session + * history are empty. Repeated requests reuse its durable identity; deleting + * that registration permanently disables automatic creation. + * @param resolveDirectory - resolve the absolute directory and initial title; + * called only for eligible creation, inside the registry mutation queue. + * Missing directories are created recursively before registration. + * @returns the initialized Workspace, or undefined when automatic creation is ineligible. + */ +initializeDefault(resolveDirectory: () => Promise<{ path: string; title: string }>): Promise + /** * Look up a workspace by id. * @param id - Workspace id. diff --git a/packages/api/workspace-controller/README.i18n.yaml b/packages/api/workspace-controller/README.i18n.yaml index cd584226a9..e7bc836965 100644 --- a/packages/api/workspace-controller/README.i18n.yaml +++ b/packages/api/workspace-controller/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/api/workspace-controller/README.md -README.md: 46556b0105bb5186cf27b56faee4127b358eac9b -README.zh.md: 9d210c10486a71772cf6c0a10480b734fa992441 +README.md: 275c51d0018dda5b2209cc7bece71b618e7d113d +README.zh.md: 92ca3f86f11ce77b51f834ce7c24f195095065b1 diff --git a/packages/api/workspace-controller/README.md b/packages/api/workspace-controller/README.md index 46556b0105..275c51d001 100644 --- a/packages/api/workspace-controller/README.md +++ b/packages/api/workspace-controller/README.md @@ -26,6 +26,18 @@ The Host controller serializes mutations whose correctness depends on current re The Client entry provides `ClientWorkspaceModel` and `createWorkspaceStateStream()`. The model owns Workspace rows, registry order, archived and pinned Session identities, unary mutation echoes, and stream/unary race resolution. A newer Host row wins by `updatedAt`; a committed stream order outranks an older unary response; a removed Workspace id cannot be resurrected by delayed data. Pin snapshots change only when their identities or order change. The package exposes framework-neutral snapshots and subscriptions, leaving navigation policy and React hooks to the UI owner. + +### First-use Workspace + +`workspace.initializeDefault({ directoryName, title })` returns the durable default Workspace; the Client service exposes the same request as `workspaces.initializeDefault(request, signal?)`. The [Conversation Client](../../client/ui-conversation/README.md) resolves these names from its send-time language. The Host places the directory under its account's `/deepseek-harness`, including on remote Web hosts. The directory name must be one non-blank segment without separators, colon, NUL, surrounding whitespace, or a trailing dot; the title must be non-blank. Linux system lookup requires `xdg-user-dir` with an enabled Documents directory. + +The [Workspace registry](../../workspace/workspace/README.md#first-use-workspace) owns eligibility, directory creation, and durable initialization. An existing default Workspace is returned without another Documents lookup; request names do not rename it. Invalid names or ineligible first use reject with `gateway/bad-request`; lookup and creation failures use standard Remote error handling. Initialization creates no Session and sends no message. + +| Configuration | Default | Purpose | +| --- | --- | --- | +| `documentsDirectory` | System Documents directory | Fully qualified Host directory override | +| `documentsLookupTimeoutMs` | `10000` | Positive maximum duration of OS directory lookup, in milliseconds | + ----- diff --git a/packages/api/workspace-controller/README.zh.md b/packages/api/workspace-controller/README.zh.md index 9d210c1048..92ca3f86f1 100644 --- a/packages/api/workspace-controller/README.zh.md +++ b/packages/api/workspace-controller/README.zh.md @@ -26,6 +26,18 @@ Host 控制器会串行执行正确性取决于当前注册表状态的变更, Client 入口提供 `ClientWorkspaceModel` 和 `createWorkspaceStateStream()`。该模型拥有 Workspace 行、registry 顺序、归档与置顶会话身份、一元变更回显,以及流与一元调用的竞态处理。较新的 Host 行按 `updatedAt` 获胜;已提交的流顺序优先于较旧的一元响应;已经移除的 Workspace id 不会被延迟数据复活。置顶快照仅在会话身份或顺序变化时更新。该包公开与框架无关的快照和订阅,把导航策略与 React 钩子留给 UI owner。 + +### 首次使用工作区 + +`workspace.initializeDefault({ directoryName, title })` 返回持久化的默认工作区;Client service 通过 `workspaces.initializeDefault(request, signal?)` 提供同一请求。[Conversation Client](../../client/ui-conversation/README.zh.md)按发送时的语言解析这些名称。Host 将目录放在其账户的 `/deepseek-harness` 下,远程 Web Host 也遵循此规则。目录名必须是非空的单个片段,不能含分隔符、冒号、NUL、首尾空白或末尾句点;标题不能为空。Linux 系统查询要求存在 `xdg-user-dir` 且启用了 Documents 目录。 + +[Workspace 注册表](../../workspace/workspace/README.zh.md#first-use-workspace)负责资格判断、目录创建和持久化初始化。已有默认工作区直接返回,不再查询 Documents;请求中的名称不会将其重命名。名称无效或不满足首次使用条件时,以 `gateway/bad-request` 拒绝;查询和创建失败遵循标准 Remote 错误处理。初始化不创建 Session,也不发送消息。 + +| 配置 | 默认值 | 用途 | +| --- | --- | --- | +| `documentsDirectory` | 系统 Documents 目录 | 完全限定的 Host 目录覆盖值 | +| `documentsLookupTimeoutMs` | `10000` | 操作系统目录查询的正数最大时长,单位为毫秒 | + ----- diff --git a/packages/api/workspace-controller/package.json b/packages/api/workspace-controller/package.json index 48881e37ce..8085412c62 100644 --- a/packages/api/workspace-controller/package.json +++ b/packages/api/workspace-controller/package.json @@ -66,6 +66,8 @@ "license": "MIT", "dependencies": { "@deepseek-ai/dsh-deque": "workspace:^", + "@deepseek-ai/dsh-native-command": "workspace:^", + "@deepseek-ai/schemastery": "workspace:^", "zod": "^4.4.3" }, "peerDependencies": { diff --git a/packages/api/workspace-controller/src/client/index.ts b/packages/api/workspace-controller/src/client/index.ts index 9a1af4c2e7..a9a98085f8 100644 --- a/packages/api/workspace-controller/src/client/index.ts +++ b/packages/api/workspace-controller/src/client/index.ts @@ -17,7 +17,7 @@ export type { } from './model.ts' export { WorkspaceController, WorkspaceCreateError } from './service.ts' export type { IWorkspaces, WorkspaceSource } from './service.ts' -export type { WorkspaceId, WorkspaceView } from '../types.ts' +export type { WorkspaceId, WorkspaceInitializeDefaultRequest, WorkspaceView } from '../types.ts' type WorkspaceBaselineFrame = Extract diff --git a/packages/api/workspace-controller/src/client/model.ts b/packages/api/workspace-controller/src/client/model.ts index 570b70aeb3..3f6dda9f76 100644 --- a/packages/api/workspace-controller/src/client/model.ts +++ b/packages/api/workspace-controller/src/client/model.ts @@ -12,6 +12,7 @@ import type { WorkspaceCreateValue, WorkspaceDeleteValue, WorkspaceInsertSessionBeforeRequest, + WorkspaceInitializeDefaultRequest, WorkspaceOrderValue, WorkspacePinSessionRequest, WorkspacePinValue, @@ -101,6 +102,18 @@ export class ClientWorkspaceModel implements WorkspaceFollowSink { return result } + /** + * Initialize the default Workspace and merge its authoritative row. + * @param request - initial directory name and title. + * @param signal - caller lifetime. + * @returns generated Remote result. + */ + async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise> { + const result = await this.remote.initializeDefault(request, signal) + if (result.ok) this.upsert(result.value.workspace) + return result + } + /** * Rename a Workspace and merge the unary result immediately. * @param workspaceId - target Workspace. diff --git a/packages/api/workspace-controller/src/client/service.ts b/packages/api/workspace-controller/src/client/service.ts index 00998f8519..f94baafdb2 100644 --- a/packages/api/workspace-controller/src/client/service.ts +++ b/packages/api/workspace-controller/src/client/service.ts @@ -4,7 +4,7 @@ import { Service, type Context } from '@deepseek-ai/cordis' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { RemoteFailure } from '@deepseek-ai/dsh-typert-protocol' import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types' -import type { WorkspaceView } from '../types.ts' +import type { WorkspaceInitializeDefaultRequest, WorkspaceView } from '../types.ts' import type { ClientWorkspaceModel, WorkspaceSnapshot } from './model.ts' /** Structured create failure for callers that distinguish Host business errors. */ @@ -39,6 +39,13 @@ export interface IWorkspaces { * @returns the created or idempotently resolved Workspace. */ create(input: { path: string }): Promise + /** + * Initialize or reuse the default Workspace. + * @param request - initial directory name and title. + * @param signal - caller lifetime. + * @returns the prepared Workspace; rejects when directory selection is required. + */ + initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise /** * Rename a Workspace. * @param workspaceId - target Workspace. @@ -110,6 +117,12 @@ export class WorkspaceController extends Service implements IWorkspaces { return result.value.workspace } + async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise { + const result = await this.model.initializeDefault(request, signal) + if (!result.ok) throw new WorkspaceCreateError(result.error) + return result.value.workspace + } + async rename(workspaceId: WorkspaceId, title: string): Promise { const result = await this.model.rename(workspaceId, title) if (!result.ok) throw commandError('rename', result.error) diff --git a/packages/api/workspace-controller/src/default-directory.ts b/packages/api/workspace-controller/src/default-directory.ts new file mode 100644 index 0000000000..2001b903c6 --- /dev/null +++ b/packages/api/workspace-controller/src/default-directory.ts @@ -0,0 +1,79 @@ +/** Resolve the Host account's Documents directory for first-use Workspace creation. */ + +import { homedir } from 'node:os' +import { posix, win32 } from 'node:path' +import { runNativeCommand, type NativeCommandRunner } from '@deepseek-ai/dsh-native-command' + +/** Platform observations replaceable in directory-resolution tests. */ +interface DocumentsDirectoryInternals { + readonly platform?: NodeJS.Platform + readonly home?: string + readonly run?: NativeCommandRunner +} + +/** + * Validate a configured or OS-returned Documents path without resolving it against cwd. + * @param directory - fully qualified directory spelling. + * @param platform - Host platform. + * @returns the normalized directory. + */ +export function validateDocumentsDirectory(directory: string, platform: NodeJS.Platform = process.platform): string { + const paths = platform === 'win32' ? win32 : posix + const root = paths.parse(directory).root + if (!paths.isAbsolute(directory) || (platform === 'win32' && (root === '\\' || root === '/'))) { + throw new Error(`Documents directory must be fully qualified: '${directory}'`) + } + return paths.normalize(directory) +} + +/** + * Resolve the first-use directory on the Host without creating files. + * @param directoryName - validated single directory name supplied by the Client. + * @param documentsDirectory - explicit deployment override for the system Documents directory. + * @param signal - caller lifetime and lookup deadline. + * @param internals - platform facts and native command runner. + * @returns the absolute candidate path. + */ +export async function defaultWorkspaceDirectory( + directoryName: string, + documentsDirectory: string | undefined, + signal: AbortSignal, + internals: DocumentsDirectoryInternals = {}, +): Promise { + const platform = internals.platform ?? process.platform + const paths = platform === 'win32' ? win32 : posix + signal.throwIfAborted() + let directory = documentsDirectory + if (directory === undefined) { + const run = internals.run ?? runNativeCommand + let stdout: string + switch (platform) { + case 'darwin': + ({ stdout } = await run('osascript', [ + '-e', 'POSIX path of (path to documents folder from user domain without folder creation)', + ], signal)) + break + case 'win32': + ({ stdout } = await run('powershell.exe', [ + '-NoLogo', '-NoProfile', '-NonInteractive', '-Command', + '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); ' + + '[Environment]::GetFolderPath([Environment+SpecialFolder]::MyDocuments, ' + + '[Environment+SpecialFolderOption]::DoNotVerify)', + ], signal)) + break + case 'linux': + ({ stdout } = await run('xdg-user-dir', ['DOCUMENTS'], signal)) + break + default: + throw new Error(`system Documents directory is unavailable on ${platform}`) + } + directory = stdout.replace(/[\r\n]+$/, '') + // XDG reports the home directory when this user directory is disabled. + if (directory === '' || (platform === 'linux' && paths.normalize(directory) === (internals.home ?? homedir()))) { + throw new Error('system Documents directory is unavailable') + } + } + directory = validateDocumentsDirectory(directory, platform) + signal.throwIfAborted() + return paths.join(directory, 'deepseek-harness', directoryName) +} diff --git a/packages/api/workspace-controller/src/index.ts b/packages/api/workspace-controller/src/index.ts index deb547e791..2281273e1e 100644 --- a/packages/api/workspace-controller/src/index.ts +++ b/packages/api/workspace-controller/src/index.ts @@ -1,10 +1,12 @@ /** Host Workspace Remote owner: explicit commands and reconnect-safe state. */ import { Context } from '@deepseek-ai/cordis' -import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' +import z from '@deepseek-ai/schemastery' +import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' import { WorkspaceCommands } from './commands.ts' import { DirectoryPickerController } from './directory-picker.ts' -import { WorkspaceFeed } from './feed.ts' +import { WorkspaceFeed, workspaceView } from './feed.ts' +import { defaultWorkspaceDirectory, validateDocumentsDirectory } from './default-directory.ts' import type { WorkspaceArchiveSessionRequest, WorkspaceArchiveValue, @@ -14,6 +16,7 @@ import type { WorkspaceDeleteValue, WorkspaceFollowFrame, WorkspaceInsertBeforeRequest, + WorkspaceInitializeDefaultRequest, WorkspaceInsertSessionBeforeRequest, WorkspaceOrderValue, WorkspacePinSessionRequest, @@ -27,6 +30,14 @@ import type { export type * from './types.ts' export { DirectoryPickerController } from './directory-picker.ts' +/** First-use directory policy for the Host account. */ +export interface Config { + /** Override the system Documents directory with a fully qualified path. */ + documentsDirectory?: string + /** Maximum duration of the operating system's Documents lookup. */ + documentsLookupTimeoutMs?: number +} + declare module '@deepseek-ai/cordis' { interface Context { /** Host Workspace business API and Remote namespace owner. */ @@ -38,12 +49,20 @@ declare module '@deepseek-ai/cordis' { export class WorkspaceController extends TypertRemoteService { static inject = ['typert', 'workspaceRegistry'] + static Config: z = z.object({ + documentsDirectory: z.string(), + documentsLookupTimeoutMs: z.natural().min(1).default(10_000), + }) + + private readonly config: Config private readonly commands: WorkspaceCommands private readonly feed: WorkspaceFeed - /** @param ctx - Host context containing the Workspace registry. */ - constructor(ctx: Context) { + /** @param ctx - Host context containing the Workspace registry. @param config - first-use directory policy. */ + constructor(ctx: Context, config: Config = {}) { super(ctx, 'workspaceController', { namespace: 'workspace' }) + this.config = WorkspaceController.Config(config) + if (this.config.documentsDirectory !== undefined) validateDocumentsDirectory(this.config.documentsDirectory) this.commands = new WorkspaceCommands(ctx) this.feed = new WorkspaceFeed(ctx) // This package is the Loader entry for both Remote owners it hosts: the @@ -63,6 +82,32 @@ export class WorkspaceController extends TypertRemoteService { return this.commands.create(request) } + /** + * Initialize or reuse the default Workspace before the first user message. + * @param request - initial directory name and title; never rename an existing default. + * @param signal - caller lifetime; cancels native directory lookup. + * @returns the durable Workspace without creating a Session or sending a message. + */ + @Remote('initializeDefault') + async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise { + const { directoryName, title } = request + if (directoryName.trim() === '' || directoryName !== directoryName.trim() + || directoryName.endsWith('.') || /[/\\:\0]/.test(directoryName) || title.trim() === '') { + throw new RemoteError('gateway/bad-request', 'default Workspace requires a directory name and non-blank title', {}) + } + const workspace = await this.ctx.workspaceRegistry.initializeDefault(async () => { + const timeout = AbortSignal.timeout(this.config.documentsLookupTimeoutMs as number) + const path = await defaultWorkspaceDirectory( + directoryName, this.config.documentsDirectory, AbortSignal.any([signal, timeout]), + ) + return { path, title } + }) + if (workspace === undefined) { + throw new RemoteError('gateway/bad-request', 'choose a directory to create a Workspace', {}) + } + return { workspace: workspaceView(workspace) } + } + /** * Rename one Workspace to a unique non-blank title. * @param request - Workspace identity and proposed title. diff --git a/packages/api/workspace-controller/src/types.ts b/packages/api/workspace-controller/src/types.ts index f2b78e024b..e69c2b8c91 100644 --- a/packages/api/workspace-controller/src/types.ts +++ b/packages/api/workspace-controller/src/types.ts @@ -54,6 +54,14 @@ export interface WorkspaceCreateRequest { readonly path: string } +/** Names chosen by the first-use Client before default Workspace initialization. */ +export interface WorkspaceInitializeDefaultRequest { + /** Single non-blank name; no separators, colon, NUL, surrounding whitespace, or trailing dot. */ + readonly directoryName: string + /** Initial display title, retained across language changes. */ + readonly title: string +} + /** Created or previously registered Workspace. */ export interface WorkspaceCreateValue { readonly workspace: WorkspaceView diff --git a/packages/api/workspace-controller/tests/default-directory.host.spec.ts b/packages/api/workspace-controller/tests/default-directory.host.spec.ts new file mode 100644 index 0000000000..5878f42432 --- /dev/null +++ b/packages/api/workspace-controller/tests/default-directory.host.spec.ts @@ -0,0 +1,48 @@ +import { describe, expect, it, vi } from 'vitest' +import type { NativeCommandRunner } from '@deepseek-ai/dsh-native-command' +import { defaultWorkspaceDirectory, validateDocumentsDirectory } from '../src/default-directory.ts' + +describe('system Documents directory', () => { + it.each([ + ['darwin', '/Users/a/文档/\n', '/Users/a/文档/deepseek-harness/默认工作区', 'osascript'], + ['win32', 'D:\\Redirected Documents\r\n', 'D:\\Redirected Documents\\deepseek-harness\\默认工作区', 'powershell.exe'], + ['linux', '/home/a/My Documents\n', '/home/a/My Documents/deepseek-harness/默认工作区', 'xdg-user-dir'], + ] as const)('uses the %s account directory and preserves spaces and Unicode', async (platform, stdout, path, command) => { + const run = vi.fn(async () => ({ stdout, stderr: '' })) + const signal = new AbortController().signal + await expect(defaultWorkspaceDirectory('默认工作区', undefined, signal, { platform, run })).resolves.toBe(path) + expect(run).toHaveBeenCalledWith(command, expect.any(Array), signal) + }) + + it.each(['Default workspace', '默认工作区', 'default-workspace'])('uses the configured directory with name %s', async (folder) => { + const run = vi.fn() + await expect(defaultWorkspaceDirectory(folder, '/documents', new AbortController().signal, { platform: 'linux', run })) + .resolves.toBe(`/documents/deepseek-harness/${folder}`) + expect(run).not.toHaveBeenCalled() + }) + + it.each(['', '\r\n', '/home/a\n'])('rejects an unavailable XDG directory %j', async (stdout) => { + const run: NativeCommandRunner = async () => ({ stdout, stderr: '' }) + await expect(defaultWorkspaceDirectory('Default workspace', undefined, new AbortController().signal, { platform: 'linux', home: '/home/a', run })) + .rejects.toThrow('unavailable') + }) + + it('propagates lookup failure and cancellation', async () => { + const run: NativeCommandRunner = async () => { throw new Error('lookup denied') } + await expect(defaultWorkspaceDirectory('Default workspace', undefined, new AbortController().signal, { platform: 'darwin', run })) + .rejects.toThrow('lookup denied') + await expect(defaultWorkspaceDirectory('Default workspace', '/documents', AbortSignal.abort(), { platform: 'linux' })) + .rejects.toThrow() + await expect(defaultWorkspaceDirectory('Default workspace', undefined, new AbortController().signal, { platform: 'freebsd' })) + .rejects.toThrow('unavailable') + }) + + it.each(['relative', 'C:relative', '\\rooted'])('rejects a Windows path without a fully qualified root: %s', (path) => { + expect(() => validateDocumentsDirectory(path, 'win32')).toThrow('fully qualified') + }) + + it('accepts redirected UNC Documents directories', () => { + expect(validateDocumentsDirectory('\\\\server\\share\\Documents', 'win32')).toBe('\\\\server\\share\\Documents') + expect(() => validateDocumentsDirectory('relative', 'linux')).toThrow('fully qualified') + }) +}) diff --git a/packages/api/workspace-controller/tests/model.client.spec.ts b/packages/api/workspace-controller/tests/model.client.spec.ts index b126805183..4558d4f64d 100644 --- a/packages/api/workspace-controller/tests/model.client.spec.ts +++ b/packages/api/workspace-controller/tests/model.client.spec.ts @@ -68,6 +68,7 @@ function deferred(): Deferred { } class FakeWorkspaceRemote implements WorkspaceRemote { + readonly initializeDefault = vi.fn(async () => remoteOk({ workspace: workspace('default') })) readonly calls: Array<{ readonly method: string; readonly request: unknown }> = [] onCreate: (request: WorkspaceCreateRequest) => Promise> = request => Promise.resolve(remoteOk({ workspace: workspace(request.path.split('/').pop() ?? 'workspace'), created: true })) @@ -167,6 +168,22 @@ function baseline( } describe('ClientWorkspaceModel', () => { + it('publishes the prepared Workspace and leaves the list unchanged on refusal', async () => { + const remote = new FakeWorkspaceRemote() + const model = modelFor(remote) + baseline(model) + const signal = new AbortController().signal + await expect(model.initializeDefault({ directoryName: '默认工作区', title: '默认工作区' }, signal)).resolves.toMatchObject({ ok: true }) + expect(remote.initializeDefault).toHaveBeenCalledWith({ directoryName: '默认工作区', title: '默认工作区' }, signal) + expect(model.getSnapshot().items.map(item => item.workspaceId)).toEqual(['default']) + const before = model.getSnapshot() + remote.initializeDefault.mockResolvedValueOnce(workspaceError( + new RemoteError('gateway/bad-request', 'choose a folder', {}), + )) + await expect(model.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' })).resolves.toMatchObject({ ok: false }) + expect(model.getSnapshot()).toBe(before) + }) + it('replaces reconnect state and applies ordered increments', () => { const model = modelFor() expect(model.getSnapshot()).toMatchObject({ phase: 'pending', state: 'loading' }) diff --git a/packages/api/workspace-controller/tests/remote/workspace.client.ts b/packages/api/workspace-controller/tests/remote/workspace.client.ts index 6857e8e31d..b8951c0c39 100644 --- a/packages/api/workspace-controller/tests/remote/workspace.client.ts +++ b/packages/api/workspace-controller/tests/remote/workspace.client.ts @@ -91,6 +91,7 @@ export function followGenerations(generations: readonly StreamScript[]): StreamS /** Default answers: every command accepted and echoed back as the row or set it names. */ export const workspaceWorld: RemoteTable = { unary: { + 'workspace/initializeDefault': (): RemoteResult => ok({ workspace: workspace('default') }), 'workspace/create': (request: WorkspaceCreateRequest): RemoteResult => ok({ workspace: workspace('created', { path: request.path }), created: true, }), diff --git a/packages/api/workspace-controller/tests/transport.client.spec.ts b/packages/api/workspace-controller/tests/transport.client.spec.ts index b99406b00c..9829004125 100644 --- a/packages/api/workspace-controller/tests/transport.client.spec.ts +++ b/packages/api/workspace-controller/tests/transport.client.spec.ts @@ -318,6 +318,7 @@ describe('WorkspaceController', () => { expect(controller.list).toBe(model) expect(client.ctx.workspaces.list).toBe(model) + await expect(controller.initializeDefault({ directoryName: '默认工作区', title: '默认工作区' }, new AbortController().signal)).resolves.toMatchObject({ workspaceId: 'default' }) await expect(controller.create({ path: '/work/created' })).resolves.toMatchObject({ workspaceId: 'created' }) await expect(controller.rename(wid('one'), 'renamed')).resolves.toMatchObject({ title: 'renamed' }) await expect(controller.insertBefore(wid('one'))).resolves.toBeUndefined() @@ -330,6 +331,7 @@ describe('WorkspaceController', () => { await expect(controller.unpinSession(sid('session'))).resolves.toBeUndefined() await expect(controller.delete(wid('one'))).resolves.toBeUndefined() // Each command crosses the wire as one positional request object. + expect(mock.log.requests('workspace/initializeDefault')).toEqual([{ directoryName: '默认工作区', title: '默认工作区' }]) expect(mock.log.requests('workspace/create')).toEqual([{ path: '/work/created' }]) expect(mock.log.requests('workspace/rename')).toEqual([{ workspaceId: 'one', title: 'renamed' }]) expect(mock.log.requests('workspace/insertBefore')).toEqual([{ workspaceId: 'one' }]) @@ -347,6 +349,9 @@ describe('WorkspaceController', () => { const missingWorkspace = new RemoteError('workspace/not-found', 'gone', { workspaceId: wid('missing') }) const missingSession = new RemoteError('session/not-found', 'missing session', { sessionId: sid('session') }) + mock.remote.workspace.initializeDefault.mockResolvedValueOnce(err(new RemoteError('gateway/internal', 'directory denied', {}))) + await expect(controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' })).rejects.toBeInstanceOf(WorkspaceCreateError) + mock.remote.workspace.create.mockResolvedValueOnce(err(new RemoteError('workspace/invalid-path', 'missing path', { path: '/missing' }))) const create = controller.create({ path: '/missing' }) await expect(create).rejects.toBeInstanceOf(WorkspaceCreateError) diff --git a/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts b/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts index 722b132255..ecaeb9a248 100644 --- a/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts +++ b/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts @@ -59,7 +59,7 @@ async function harness() { lookups: { configure: () => dispose }, contexts: { configureHost: () => dispose }, } as never) - const controller = new WorkspaceController(ctx) + const controller = new WorkspaceController(ctx, { documentsDirectory: root }) return { controller, ctx, root, storageDomain } } @@ -416,3 +416,49 @@ describe('WorkspaceController follow', () => { await expect(closing).resolves.toEqual({ done: true, value: undefined }) }) }) + +describe('first-use Remote', () => { + it.each(['', ' ', '.', '..', '../outside', 'nested/name', 'nested\\name', 'C:outside', 'name\0', '.. ', 'tail.'])( + 'rejects invalid directory name %j before invoking the registry', async (directoryName) => { + const { controller, ctx } = await harness() + const initialize = vi.spyOn(ctx.workspaceRegistry, 'initializeDefault').mockResolvedValue(undefined) + await expect(controller.initializeDefault({ directoryName, title: 'Default workspace' }, new AbortController().signal)) + .rejects.toMatchObject({ code: 'gateway/bad-request' }) + expect(initialize).not.toHaveBeenCalled() + }, + ) + + it('rejects a blank initial title before invoking the registry', async () => { + const { controller, ctx } = await harness() + const initialize = vi.spyOn(ctx.workspaceRegistry, 'initializeDefault').mockResolvedValue(undefined) + await expect(controller.initializeDefault({ directoryName: 'default-workspace', title: ' ' }, new AbortController().signal)) + .rejects.toMatchObject({ code: 'gateway/bad-request' }) + expect(initialize).not.toHaveBeenCalled() + }) + + it('uses the requested display title independently of the directory name', async () => { + const { controller, root } = await harness() + const result = await controller.initializeDefault({ directoryName: 'default-workspace', title: 'Default workspace' }, new AbortController().signal) + expect(result.workspace).toMatchObject({ path: join(root, 'deepseek-harness', 'default-workspace'), title: 'Default workspace' }) + }) + + it('returns a durable Workspace without allocating a Session', async () => { + const { controller, ctx, root } = await harness() + const signal = new AbortController().signal + const result = await controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' }, signal) + expect(result.workspace.path).toBe(join(root, 'deepseek-harness', 'Default workspace')) + expect(existsSync(result.workspace.path)).toBe(true) + expect(ctx.sessions.list()).toEqual([]) + expect(await controller.initializeDefault({ directoryName: '默认工作区', title: '默认工作区' }, signal)).toEqual(result) + }) + + it('rejects ineligible first use and propagates preparation failures', async () => { + const { controller, ctx, root } = await harness() + await ctx.workspaceRegistry.create(root) + await expect(controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' }, new AbortController().signal)) + .rejects.toMatchObject({ code: 'gateway/bad-request' }) + vi.spyOn(ctx.workspaceRegistry, 'initializeDefault').mockRejectedValueOnce(new Error('permission denied')) + await expect(controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' }, new AbortController().signal)) + .rejects.toThrow('permission denied') + }) +}) diff --git a/packages/api/workspace-controller/tsconfig.host.json b/packages/api/workspace-controller/tsconfig.host.json index 10c17a0c23..17fda7ee38 100644 --- a/packages/api/workspace-controller/tsconfig.host.json +++ b/packages/api/workspace-controller/tsconfig.host.json @@ -10,15 +10,18 @@ "src/types.ts", "src/commands.ts", "src/directory-picker.ts", - "src/feed.ts" + "src/feed.ts", + "src/default-directory.ts" ], "references": [ { "path": "../../../vendor/cordis" }, + { "path": "../../../vendor/schemastery" }, { "path": "../../core/session" }, { "path": "../../host/directory-picker" }, { "path": "../../storage/storage-domain" }, { "path": "../../typert/protocol" }, { "path": "../../util/deque" }, + { "path": "../../util/native-command" }, { "path": "../../workspace/workspace" } ] } diff --git a/packages/client/ui-agent-preset/README.i18n.yaml b/packages/client/ui-agent-preset/README.i18n.yaml index 2ed6513974..7f0a28c544 100644 --- a/packages/client/ui-agent-preset/README.i18n.yaml +++ b/packages/client/ui-agent-preset/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-agent-preset/README.md -README.md: c7a87da591c1cafc433fbb3bb5fa216d94ab85ef -README.zh.md: a54b47baed132e790fc4f44ad1155f48a19c430b +README.md: 38eba97e2c11ed319a9a5724bece1fbbd1f8095a +README.zh.md: 730c363c0876c6f6bc9ee8565aeb922526ed8f3d diff --git a/packages/client/ui-agent-preset/README.md b/packages/client/ui-agent-preset/README.md index c7a87da591..38eba97e2c 100644 --- a/packages/client/ui-agent-preset/README.md +++ b/packages/client/ui-agent-preset/README.md @@ -49,6 +49,8 @@ The settings section writes the Host's existing `agent-presets` namespace throug The chip follows the preset projection of its bound Session while its plugin and Provider generation remain active. Settings synchronization creates the same bound controller when needed, even before the chip mounts. A late projection or another client's preset update refreshes the display without submitting a selection; list notifications do not repeat an in-flight selection. Settings changes wait for that selection and recheck the captured blank Session before applying. A choice staged during a pending request remains available afterward. +After preparing a default Workspace, the first-use draft waits for the staged preset through `conversation/prepare-first-send`. Concurrent `apply()` calls wait for the active selection without repeating it. A refusal keeps the unsent Session draft. + ----- diff --git a/packages/client/ui-agent-preset/README.zh.md b/packages/client/ui-agent-preset/README.zh.md index a54b47baed..730c363c08 100644 --- a/packages/client/ui-agent-preset/README.zh.md +++ b/packages/client/ui-agent-preset/README.zh.md @@ -49,6 +49,8 @@ kind: "package-reference" 只要插件及 Provider generation 仍有效,选择芯片就会跟随其绑定 Session 的预设投影。即使选择芯片尚未挂载,设置同步也会按需创建同一个绑定控制器。延后到达的投影或其他客户端的预设更新会刷新显示,而不会提交选择;列表通知不会重复仍在进行中的选择操作。设置修改会等待该操作结束,并在应用之前重新检查已捕获的空白 Session。请求期间暂存的新选择会保留。 +默认工作区准备完成后,首次使用的草稿通过 `conversation/prepare-first-send` 等待暂存的模式选择。并发的 `apply()` 调用等待已有选择操作,不会重复提交。选择被拒绝时保留未发送的 Session 草稿。 + ----- diff --git a/packages/client/ui-agent-preset/src/client/index.ts b/packages/client/ui-agent-preset/src/client/index.ts index c335518aff..bc8631e577 100644 --- a/packages/client/ui-agent-preset/src/client/index.ts +++ b/packages/client/ui-agent-preset/src/client/index.ts @@ -143,6 +143,14 @@ export function apply(ctx: ClientContext): void { // render and simply hides the button while no flow exists. let creatorDraft: (() => void) | undefined ctx.inject(['slots', 'conversation', 'sessions', 'uiWorkspace'], (scope: ClientContext) => { + scope.on('conversation/prepare-first-send', async (sessionId) => { + const binding = scope.sessions.binding(sessionId) + if (binding === undefined) return + const seat = seatFor(binding) + if (staged.id === undefined && !seat.store.getSnapshot().busy) return + const error = await seat.apply() + if (error !== undefined) throw new Error(error) + }) const seatInjected = (sessionId: SessionId | undefined): AgentPresetSeatInjected => { const binding = sessionId === undefined ? undefined : ctx.sessions.binding(sessionId) const seat = binding === undefined ? unboundSeat : seatFor(binding) diff --git a/packages/client/ui-agent-preset/src/client/seat-store.ts b/packages/client/ui-agent-preset/src/client/seat-store.ts index 45bd9373e4..4e7488bc3b 100644 --- a/packages/client/ui-agent-preset/src/client/seat-store.ts +++ b/packages/client/ui-agent-preset/src/client/seat-store.ts @@ -193,11 +193,18 @@ export class AgentPresetSeatController { * * Called both by `select()` and by whoever observes the current session * changing, because the session may appear either before or after the pick. - * List updates do not repeat a selection while its response is pending. - * @returns this attempt's Host refusal, or undefined when successful or no switch starts. + * Concurrent callers wait for the active selection without repeating it. + * @returns the Host refusal, or undefined when successful or no switch starts. */ async apply(): Promise { - if (this.store.getSnapshot().busy) return + let pending = this.pendingSelection + while (pending !== undefined) { + await pending + const error = this.store.getSnapshot().error + if (error !== null) return error + pending = this.pendingSelection + if (pending === undefined && this.staged.id === undefined) return + } const staged = this.staged.id const session = this.currentSession() if (staged === undefined) { diff --git a/packages/client/ui-agent-preset/tests/apply.client.spec.ts b/packages/client/ui-agent-preset/tests/apply.client.spec.ts index 1e28cb44f4..ea312699ce 100644 --- a/packages/client/ui-agent-preset/tests/apply.client.spec.ts +++ b/packages/client/ui-agent-preset/tests/apply.client.spec.ts @@ -747,10 +747,12 @@ describe('ui-agent-preset apply', () => { } sessions.notify() const bound = injectSeat(SessionId('s1')) + await ctx.serial('conversation/prepare-first-send', SessionId('s1')) await bound.load() // Connecting a workspace produced the session; the stage reaches it there. await vi.waitFor(() => { expect(calls).toContain('select:minimal') }) + expect(calls.filter(call => call === 'select:minimal')).toHaveLength(1) }) it('applies the stage to a session that records no preset of its own', async () => { @@ -946,6 +948,28 @@ describe('ui-agent-preset apply', () => { }) describe('AgentPresetSeatController reconciliation', () => { + it.each([false, true])('shares the result of an active preset selection (refused: %s)', async (refused) => { + const refusal = { ok: false as const, error: new RemoteError('gateway/internal', 'selection refused', {}) } + const reply = Promise.withResolvers<{ ok: true; value: string } | typeof refusal>() + const select = vi.fn(() => reply.promise) + const controller = new AgentPresetSeatController({ remote: { agentPresets: { select } } } as never, + () => ({ id: SessionId('blank'), blank: true, projectionValues: { agentPreset: 'standard' } })) + const selecting = controller.select('minimal') + let prepared = false + const preparation = controller.apply().finally(() => { prepared = true }) + try { + expect(prepared).toBe(false) + expect(select).toHaveBeenCalledOnce() + reply.resolve(refused ? refusal : { ok: true, value: 'minimal' }) + await expect(preparation).resolves.toBe(refused ? 'selection refused' : undefined) + await selecting + expect(select).toHaveBeenCalledOnce() + } finally { + reply.resolve({ ok: true, value: 'minimal' }) + await Promise.allSettled([selecting, preparation]) + } + }) + it.each([ { refuseFirst: false, refuseLatest: false }, { refuseFirst: false, refuseLatest: true }, @@ -966,16 +990,17 @@ describe('AgentPresetSeatController reconciliation', () => { const first = controller.select('minimal') let settingsSettled = false const settings = controller.syncBlankSession(session.id, 'cordis').finally(() => { settingsSettled = true }) - await controller.apply() + const repeatedFirst = controller.apply() expect(requests.map(request => request.preset)).toEqual(['minimal']) requests[0]!.outcome.resolve(refuseFirst ? refusal : { ok: true, value: 'minimal' }) await first expect(requests.map(request => request.preset)).toEqual(['minimal', 'cordis']) expect(settingsSettled).toBe(false) - await controller.apply() + const repeatedLatest = controller.apply() expect(requests).toHaveLength(2) requests[1]!.outcome.resolve(refuseLatest ? refusal : { ok: true, value: 'cordis' }) await expect(settings).resolves.toBe(refuseLatest ? 'selection refused' : undefined) + await Promise.all([repeatedFirst, repeatedLatest]) expect(controller.store.getSnapshot()).toMatchObject({ current: refuseLatest ? 'standard' : 'cordis', busy: false, error: refuseLatest ? 'selection refused' : null, @@ -992,10 +1017,10 @@ describe('AgentPresetSeatController reconciliation', () => { () => ({ id: SessionId('blank'), blank: true, projectionValues: { agentPreset: 'standard' } })) const first = controller.select('minimal') controller.stage('cordis', true) - await controller.apply() + const repeated = controller.apply() expect(select).toHaveBeenCalledOnce() firstReply.resolve(refused ? refusal : { ok: true, value: 'minimal' }) - await first + await Promise.all([first, repeated]) expect(controller.store.getSnapshot().current).toBe('cordis') await controller.apply() expect(select.mock.calls.map(call => call[1])).toEqual(['minimal', 'cordis']) diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 74cd3168df..2002de04c1 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md -README.md: fef3a6551b517af2ac636687883864525aac70ee -README.zh.md: e9ab08c686420c38c11ca2bede2fd00099a247a5 +README.md: 56b9d06ce5e48ab40691bede2ccb9669e180aa9f +README.zh.md: fd02565698171e0b6db35080181e57b8b5abd42d diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index fef3a6551b..56b9d06ce5 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -50,6 +50,10 @@ Claimed commands retain their identity and highlight when only their arguments a Workspace selection uses `uiWorkspace.openWorkspace` to prepare the target and commit navigation. Draft text and attachments move in its synchronous preparation callback only while that request is current; later navigation or owner disposal leaves the original draft intact. +The Client chooses the default directory name and initial title when sending: Chinese uses `默认工作区`, English uses `Default workspace`, and other languages use directory `default-workspace` with title `Default workspace`. The request retains those names during initialization. A retry after failed initialization uses the current language; a successfully initialized Workspace keeps its directory and title across language changes. + +On first use, the same input accepts text before a Workspace is selected. The first send prepares the [default Workspace](../../workspace/workspace/README.md#first-use-workspace), selects its blank Session, transfers the draft, and uses ordinary message submission. Preparation locks further input. Failure preserves the draft and offers Cancel or Choose folder through the existing picker. A manually chosen folder receives the unsent draft; the user sends again. Once created, the Workspace survives a prompt failure. `conversation/prepare-first-send` awaits staged Session settings before automatically submitting the transferred first-use draft; a rejected listener keeps that draft and reports its error. + The package occupies the root-scoped `main` key `conversation`. Its `main.conversation` shell keeps the resident `conversation.header` outside the optional-Session `conversation.content` Component Factory. The header hosts root-scoped navigation without a selected Session; titles, actions, and View tabs remain in its strict Session child. The Factory owns the shared body and Composer, reads the current Session through its standard Hook, and exposes strict-Session `views` plus root-scoped `widthControls` local positions. Its default adapter renders the existing `conversation.session` entry, while the main occurrence selects the width handles; an embedded occurrence can replace `views` and omit those handles without rendering the main Header. The shared body and Composer register the queue and Todo docks. The Todo dock uses the shared panel elevation above the composer; its rows use the shared idle, ongoing, and done markers for pending, in-progress, and completed items. `ctx.uiSession.provide()` materializes the Conversation and input sources from the same Session binding and supplies `inputActions` as a stable standard prop. A blank Session retains the header's leading and corner controls, including the right-sidebar opener, while hiding its title, actions, utilities, and View tabs. Selecting a Workspace creates the Session needed by these controls; the first message is not required. Without a selected Session, the strict header is absent; the resident container reserves a 40px drag band on macOS desktop and no empty vertical space on Web, Windows, or Linux. Sidebar entries retain their own data and execution prerequisites. A started Session header uses one row when fewer than two Views are available; the tab row reserves space only while rendered. @@ -60,7 +64,7 @@ The shell reads the persisted View preference before rendering when a Session fi Active transcripts in the main occurrence expose content-width drag handles in their uncovered side gutters; embedded occurrences omit them. A View that paints into a gutter raises only its concrete painted element above the handle; transparent full-width wrappers stay below so they do not claim empty gutter. This requires the path between that element and the Conversation body to remain outside an intermediate stacking context; the shipped Chromium behavior is pinned by the browser scenario. Chat applies the rule to table elements, while its column-bounded tool cards need no raise. Wheel motion over a handle still scrolls the transcript, while Ctrl+wheel remains a browser zoom gesture. The sticky composer intentionally owns its full footer band, which is not a resize target; an already-captured drag lifts its indicator until release ([handle styles](src/client/skeleton/ConversationRoot.module.css)). -The resident composer survives no-Session and Session transitions. Whitespace hides its placeholder; a whitespace-only draft without attachments cannot be sent. The no-Session state keeps the same composer surface mounted but inert while the Workspace picker connects a blank Session. The surface is a shell-owned Lexical editor: reference chips are atomic decorator nodes carrying the owner's serialization identity (submission expands them through the owner codec), claimed slash commands stay styled leading text, folder text references carry the folder glyph as an icon prefix, and the draft's clipboard projection is mirrored into the per-Session Conversation store. QueueDock reads `next-turn` directly from the Session `inbox` projection, including cold recovered messages. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews render sent text through the shared inline reference projection from `ui-primitives` (wire session forms fold to their label) and show local or durable images and files in original attachment order. Images use thumbnails; files use compact name-and-size cards. An edit exposes the literal sent text, and durable thumbnails resolve through the session image URL cache. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace. The composer keymap arbitrates the trigger menu's keys through the slash pipeline — Tab settles the highlighted completion (or drills a drillable one), Escape and Shift+Tab leave the menu without settling — and leaves every other key to the editor. An overlay that takes the keyboard hands it back through `SessionInput.focus()`, which rides Lexical's own focus so the caret returns where the draft left it rather than at the start. +The resident composer survives no-Session and Session transitions. Whitespace hides its placeholder; a whitespace-only draft without attachments cannot be sent. Before a Session exists, the composer holds a local text draft; sending waits for complete Workspace and Session baselines and then prepares the default Workspace. The surface is a shell-owned Lexical editor: reference chips are atomic decorator nodes carrying the owner's serialization identity (submission expands them through the owner codec), claimed slash commands stay styled leading text, folder text references carry the folder glyph as an icon prefix, and the draft's clipboard projection is mirrored into the per-Session Conversation store. QueueDock reads `next-turn` directly from the Session `inbox` projection, including cold recovered messages. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews render sent text through the shared inline reference projection from `ui-primitives` (wire session forms fold to their label) and show local or durable images and files in original attachment order. Images use thumbnails; files use compact name-and-size cards. An edit exposes the literal sent text, and durable thumbnails resolve through the session image URL cache. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace. The composer keymap arbitrates the trigger menu's keys through the slash pipeline — Tab settles the highlighted completion (or drills a drillable one), Escape and Shift+Tab leave the menu without settling — and leaves every other key to the editor. An overlay that takes the keyboard hands it back through `SessionInput.focus()`, which rides Lexical's own focus so the caret returns where the draft left it rather than at the start. Default sends commit optimistically: Enter clears the draft, occurrence table, and undo history in the same transaction, keeps the composer in `plain`, and runs the send as a detached attempt, so typing and further sends continue during the flight. `sendSession` registers a Session submission echo (`session.beginSubmission`) with the delivery mode before serializing, preserving selected image and file order in `pendingSubmissions`; Session derives the placement from that mode and its current running state, so idle sends use the transcript, busy Queue sends use QueueDock, and busy Steer sends use the pending-steering surface. It then yields one paint, encodes images through the browser's native `FileReader` data-URL path, and cites staged file receipts. Command submissions use the same receipts for generic files, so sending `/goal` or `/plan` never reads those browser files again. The prompt reuses the submission `requestId`; queue and history observation by that `rpcId` retires the echo once. Concurrent failures are restored together in submission order until the user edits the restored content; command submissions keep the frozen `submitting` phase. Detached attempts retain their attachment ids through admission and Session scope disposal. An observed retirement immediately exposes each image preview through the durable cache, replaces it with the canonical URL after fetching the admitted attachment, revokes each URL after its use ends, and releases file cards. Selected generic files enter one FIFO background-upload queue; `maxConcurrentFileUploads` defaults to two active Worker transports, the Conversation service retains queued and active operations plus byte progress across Session navigation, and removing a draft skips its queued transfer or aborts its active transport. Continuable subagents disable attachment intake and skip local echoes because their transport does not preserve the browser request id. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index e9ab08c686..fd02565698 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -50,6 +50,10 @@ target package 通过 declaration merge 扩展 snapshot 与 Location data map, 工作区选择使用 `uiWorkspace.openWorkspace` 准备目标并提交导航。草稿文字和附件仅在该请求仍为当前请求时,通过它的同步准备回调搬移;后续导航或所有者释放会保留原草稿。 +Client 在发送时决定默认目录名和初始标题:中文使用 `默认工作区`,英文使用 `Default workspace`,其他语言使用目录 `default-workspace` 和标题 `Default workspace`。初始化期间,请求保留这些名称。初始化失败后的重试使用当前语言;初始化成功的 Workspace 在切换语言后仍保留原目录和标题。 + +首次使用时,同一个输入框允许在选择 Workspace 前输入文字。首条消息会准备[默认工作区](../../workspace/workspace/README.zh.md#first-use-workspace)、选中其 blank Session、转移草稿,再使用普通消息提交流程。准备期间锁定后续输入。失败时保留草稿,并提供“取消”或通过已有选择器“选择文件夹”。手动选择的文件夹接收未发送草稿,用户再次发送。Workspace 创建成功后,不会因提示词发送失败而消失。`conversation/prepare-first-send` 在自动提交已转移的首次使用草稿前等待暂存的 Session 设置完成;监听器拒绝时保留该草稿并显示错误。 + 本包占据 root 作用域 `main` 中的 `conversation` key。其 `main.conversation` 外壳将常驻的 `conversation.header` 放在可选 Session 的 `conversation.content` Component Factory 外。未选中 Session 时,头部仍承载根作用域导航;标题、操作和 View 标签保留在严格 Session 子组件中。Factory 拥有共享正文与 Composer,通过其标准 Hook 读取当前 Session,并公开 strict-Session `views` 与 root-scoped `widthControls` 两个局部位置。默认 adapter 渲染现有 `conversation.session` entry,主 occurrence 选择宽度拖拽条;嵌入式 occurrence 可以替换 `views`、省略拖拽条,且不渲染主 Header。共享正文与 Composer 注册 queue dock 和 Todo dock。Todo dock 在 composer 上方使用共享面板 elevation;其中的行分别以共享 idle、ongoing 与 done 标记表示待处理、进行中与已完成。`ctx.uiSession.provide()` 从同一个 Session binding 物化 Conversation 与 input source,并将 `inputActions` 作为稳定标准 prop 提供。 blank Session 保留 header 的 leading 与 corner 控件,包括右侧栏展开入口,同时隐藏标题、actions、utilities 和 View tabs。选择 Workspace 会创建这些控件所需的 Session,无需先发送消息。没有选中 Session 时,strict header 不挂载;常驻容器在 macOS 桌面保留 40px 拖拽区域,在 Web、Windows 或 Linux 上不预留空白高度。侧栏各入口仍遵循自身的数据与执行环境要求。 已开始的 Session 在可用 View 少于两个时使用单行标题栏,仅在渲染标签行时保留其高度。 @@ -60,7 +64,7 @@ Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染 主 occurrence 的活跃 transcript 只在未被内容覆盖的两侧沟槽中提供正文宽度拖拽条;嵌入式 occurrence 省略这些拖拽条。View 如果绘制进沟槽,只将具体的可见元素提到拖拽条上方;透明的全宽包装层保持在下方,不会占用空白沟槽。该规则要求此元素与 Conversation body 之间不能引入中间堆叠上下文;浏览器场景固定了交付 Chromium 的行为。Chat 将该规则用于表格元素,其限定在阅读列内的工具卡片无需提高层级。指针位于拖拽条上时,滚轮仍会滚动 transcript,Ctrl+滚轮则保留为浏览器缩放手势。粘滞 composer 刻意拥有完整的底部区带,该区域不是宽度调整目标;已捕获的拖拽会将指示线提高到松开为止([拖动手柄样式](src/client/skeleton/ConversationRoot.module.css))。 -常驻 composer 在无 Session 与有 Session 之间保持挂载。输入空白字符会隐藏占位提示;没有附件的纯空白草稿无法发送。无 Session 时,同一个编辑器表面保持 inert,Workspace picker 连接 blank Session。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 保持为带样式的行首文本,文件夹文本引用以图标前缀携带文件夹图形,草稿的剪贴板投影镜像到逐 Session Conversation store。QueueDock 直接从 Session 的 `inbox` 投影读取 `next-turn`,包含从冷状态恢复的消息。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览经 `ui-primitives` 的共享行内引用投影渲染已发送文本(wire 会话形式折叠为其标签),并按原始附件顺序展示本地或持久化的图片和文件。图片使用缩略图,文件使用紧凑的名称与大小卡片。编辑态展示字面发送文本,持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。 composer 键盘映射经斜杠流水线裁决触发菜单的按键——Tab 确认高亮补全项(可下钻项则下钻),Escape 与 Shift+Tab 离开菜单且不选定——其余按键交给编辑器自身。 接管键盘的浮层通过 `SessionInput.focus()` 把键盘还回来,该路径走 Lexical 自己的 focus,因此光标回到草稿原来的位置而不是开头。 +常驻 composer 在无 Session 与有 Session 之间保持挂载。输入空白字符会隐藏占位提示;没有附件的纯空白草稿无法发送。Session 尚未存在时,composer 保存本地文字草稿;发送会等待 Workspace 与 Session 基线完整加载,然后准备默认工作区。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 保持为带样式的行首文本,文件夹文本引用以图标前缀携带文件夹图形,草稿的剪贴板投影镜像到逐 Session Conversation store。QueueDock 直接从 Session 的 `inbox` 投影读取 `next-turn`,包含从冷状态恢复的消息。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览经 `ui-primitives` 的共享行内引用投影渲染已发送文本(wire 会话形式折叠为其标签),并按原始附件顺序展示本地或持久化的图片和文件。图片使用缩略图,文件使用紧凑的名称与大小卡片。编辑态展示字面发送文本,持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。 composer 键盘映射经斜杠流水线裁决触发菜单的按键——Tab 确认高亮补全项(可下钻项则下钻),Escape 与 Shift+Tab 离开菜单且不选定——其余按键交给编辑器自身。 接管键盘的浮层通过 `SessionInput.focus()` 把键盘还回来,该路径走 Lexical 自己的 focus,因此光标回到草稿原来的位置而不是开头。 默认发送采用乐观提交:Enter 在同一事务里清空草稿、occurrence 表和撤销历史,composer 保持 `plain`,发送作为 detached attempt 运行,发送期间可以继续输入和提交。`sendSession` 在序列化之前用投递模式注册 Session 提交回显(`session.beginSubmission`),并在 `pendingSubmissions` 中保留图片与文件的选择顺序;Session 根据该模式与当前运行状态推导位置,因此空闲发送进入 transcript(文本记录),繁忙时 Queue 进入 QueueDock,繁忙时 Steer 进入 pending-steering 区域。随后让出一帧,图片经浏览器原生 `FileReader` data-URL 路径编码,文件则引用已暂存凭证。命令提交也用同一凭证表示通用文件,因此发送 `/goal` 或 `/plan` 时不会再次读取这些浏览器文件。提示词复用提交 `requestId`;queue 或历史以同一 `rpcId` 被观察后,回显只退休一次。多个并发发送失败时,在用户编辑还原内容之前按提交顺序合并还原;命令提交保持冻结的 `submitting` 阶段。Detached attempt 持有附件 id,直到 admission 完成或 Session scope 销毁。回显以 observed 退休时,durable 图片缓存立即公开每个预览 URL,读取 admitted 附件后用规范化 URL 替换预览,并在各 URL 停止使用后撤销,同时释放文件卡。选中的通用文件进入同一个先进先出的后台上传队列;`maxConcurrentFileUploads` 默认允许两个 Worker transport 同时运行,Conversation 服务在切换 Session 时继续持有排队和运行中的传输操作及字节进度,移除草稿会跳过排队中的传输或中止正在运行的传输。continuable 子代理禁用附件入口,也不创建本地回显,因为其 transport 不保留浏览器 request id。 diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index 3fef945990..02c1f3a593 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -2,6 +2,7 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type { ISessions, SessionBinding } from '@deepseek-ai/dsh-api-session-controller/client' +import type { WorkspaceInitializeDefaultRequest } from '@deepseek-ai/dsh-api-workspace-controller/client' import { IconPaperclipOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import { createSnapshotStore, type BoundActions } from '@deepseek-ai/dsh-client-store' import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' @@ -17,13 +18,13 @@ import type { ComposerBarInjected, ConversationInjected, ConversationSessionHeaderInjected, ConversationSessionInjected, DraftFileUploads, } from './contract/slots.ts' -import type { InputNotice } from './contract/input.ts' import { createConversationStore, readConversationViewPreference } from './stores.ts' import { ConversationController, UnsupportedImageMediaTypeError } from './service.ts' import type { IConversation } from './service.ts' import { ComposerBlockRegistry } from './input/blocks.ts' import type { ComposerBlock } from './contract/composer-blocks.ts' import { InputHub } from './input/hub.ts' +import { FirstDraft } from './input/first-draft.ts' import { ComposerSubmissionPolicy } from './input/submission-policy.ts' import { queueDockEntry } from './queue/QueueDock.tsx' import { EnterBehaviorRow } from './settings/EnterBehaviorRow.tsx' @@ -64,19 +65,10 @@ export const Config: z = z.object({ // Stable no-session sources keep the renderer's observable-hook cache and // hook order unchanged across current-Session transitions. -const ABSENT_NOTICES = { - getSnapshot: (): InputNotice | null => null, - subscribe: () => () => {}, -} const ABSENT_BLOCK = { getSnapshot: (): ComposerBlock | undefined => undefined, subscribe: () => () => {}, } -const EMPTY_LEXICON: ReadonlyMap<'/' | '@', readonly string[]> = new Map() -const ABSENT_LEXICON = { - getSnapshot: () => EMPTY_LEXICON, - subscribe: () => () => {}, -} const ABSENT_MENU_LAUNCHER = { getSnapshot: (): string | null => null, subscribe: () => () => {}, @@ -87,12 +79,19 @@ const ABSENT_FILE_UPLOADS = { subscribe: () => () => {}, } +// ui-workspace consumes Conversation slots, so this reverse runtime dependency +// uses a local method projection to keep the TypeScript project graph acyclic. interface WorkspaceNavigation { openSession(sessionId: SessionId): void openWorkspace( workspaceId: Parameters[0], beforeOpen: (sessionId: SessionId) => void, ): Promise + openDefaultWorkspace( + request: WorkspaceInitializeDefaultRequest, + beforeOpen: (sessionId: SessionId) => void, + signal: AbortSignal, + ): Promise } /** Action registration used by the composer without importing its command-UI consumer. */ @@ -206,6 +205,17 @@ export function apply(ctx: Context, config: Config = Config({})): void { }, 'ui-conversation: View selection') const inputHub = new InputHub(ctx, t) + const firstDraft = new FirstDraft(ctx, { + open: (beforeOpen, signal) => { + const language = ctx.locale.getSnapshot().active.toLowerCase().split('-')[0] + const title = (language === 'zh' ? zh : en)['defaultWorkspace.title'] + return workspaceNavigation.openDefaultWorkspace({ + directoryName: language === 'zh' || language === 'en' ? title : 'default-workspace', + title, + }, beforeOpen, signal) + }, + shell: id => inputHub.shell(id), + }) const composerBlocks = new ComposerBlockRegistry() ctx.inject(['commandUi'], (scope) => { @@ -266,8 +276,11 @@ export function apply(ctx: Context, config: Config = Config({})): void { inject: (sessionId: SessionId | undefined): ConversationInjected => ({ hooks: { composerBlock: sessionId === undefined ? ABSENT_BLOCK : composerBlocks.storeFor(sessionId), + firstDraft: firstDraft.state, }, + dismissDefaultFailure: () => { firstDraft.dismiss() }, selectWorkspace: workspaceId => workspaceNavigation.openWorkspace(workspaceId, (nextId) => { + if (sessionId === undefined) firstDraft.transfer(nextId) if (sessionId !== undefined && nextId !== sessionId) { const from = inputHub.shell(sessionId) const draft = from.snapshot.draft @@ -373,7 +386,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { inject: (sessionId: SessionId | undefined): ComposerBarInjected => { if (sessionId === undefined) { return { - keyboard: undefined, + keyboard: firstDraft.shell, addFiles: undefined, removeAttachment: undefined, resolveDraftAttachments: undefined, @@ -381,10 +394,11 @@ export function apply(ctx: Context, config: Config = Config({})): void { toggleCommandMenu: undefined, stop: undefined, hooks: { + composerInput: firstDraft.shell.state, busyEnter: submissionPolicy.busyEnter, fileUploads: ABSENT_FILE_UPLOADS, - notices: ABSENT_NOTICES, - lexicon: ABSENT_LEXICON, + notices: firstDraft.shell.notices, + lexicon: firstDraft.shell.lexicon, menuLauncher: ABSENT_MENU_LAUNCHER, }, } @@ -433,6 +447,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { }) }, hooks: { + composerInput: shell.state, busyEnter: submissionPolicy.busyEnter, fileUploads: conversation.fileUploads, notices: shell.notices, diff --git a/packages/client/ui-conversation/src/client/contract/input.ts b/packages/client/ui-conversation/src/client/contract/input.ts index b4cd6b9bdf..be338eb3df 100644 --- a/packages/client/ui-conversation/src/client/contract/input.ts +++ b/packages/client/ui-conversation/src/client/contract/input.ts @@ -34,6 +34,12 @@ export interface SubmitOutcome { readonly text?: string } +/** State of first-use Workspace preparation. */ +export interface FirstDraftState { + readonly busy: boolean + readonly failed: boolean +} + /** Command-mode credential supplied by one input-trigger source. */ export interface CommandClaim { /** Catalog command name without the leading slash (the key of per-command composer copy such as `hint.*`). */ diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index 023babf26e..a0d9a6d592 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -16,7 +16,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types' import type { ComposerBlock } from './composer-blocks.ts' -import type { DraftAttachmentId, InputActions, InputNotice, InputState } from './input.ts' +import type { DraftAttachmentId, FirstDraftState, InputActions, InputNotice, InputState } from './input.ts' import type { ComposerKeyboard, EditSelection } from './draft-editor.ts' import type { createConversationStore } from '../stores.ts' import type { BusyEnterBehavior } from './composer-submission.ts' @@ -319,8 +319,13 @@ export type ConvViewProps = PropsRuntime<'conversation.view'> export interface ConversationInjected { /** Connect and open a blank Session in the selected Workspace. */ selectWorkspace: (workspaceId: WorkspaceId) => Promise + /** Dismiss default Workspace creation failure without discarding input. */ + dismissDefaultFailure: () => void /** Session-addressed composer block source, or the stable absent source. */ - hooks: { composerBlock: ObservableSnapshot } + hooks: { + composerBlock: ObservableSnapshot + firstDraft: ObservableSnapshot + } } /** Business callbacks injected into the strict Session body. */ @@ -365,7 +370,7 @@ export interface ComposerBarOwnerProps { /** Package-private operations injected into the resident composer bar. */ export interface ComposerBarInjected { - keyboard: ComposerKeyboard | undefined + keyboard: ComposerKeyboard addFiles: ((files: readonly File[]) => string | null) | undefined removeAttachment: ((id: DraftAttachmentId) => void) | undefined resolveDraftAttachments: ((ids: readonly DraftAttachmentId[]) => readonly ComposerAttachment[]) | undefined @@ -374,6 +379,8 @@ export interface ComposerBarInjected { toggleCommandMenu: ((selection: EditSelection) => void) | undefined stop: (() => void) | undefined hooks: { + /** Resident editor state, including input before a Session exists. */ + composerInput: ObservableSnapshot /** * Live busy-state submission preference: the delivery mode plain Enter * and the primary Send button use while the addressed agent is busy. diff --git a/packages/client/ui-conversation/src/client/index.ts b/packages/client/ui-conversation/src/client/index.ts index 73ddc6d7d3..468fc9c198 100644 --- a/packages/client/ui-conversation/src/client/index.ts +++ b/packages/client/ui-conversation/src/client/index.ts @@ -72,6 +72,14 @@ export type { ArbitrateKey, ArbitrateOutcome, ReferenceInsert, TokenSpan } from export type { ComposerBlock, ComposerBlocks } from './contract/composer-blocks.ts' declare module '@deepseek-ai/cordis' { + interface Events { + /** + * Finish staged settings before automatically submitting the first-use draft to its new Session. + * @mode serial + * @param sessionId - destination Session. + */ + 'conversation/prepare-first-send'(sessionId: import('@deepseek-ai/dsh-session/types').SessionId): void | Promise + } interface Context { /** Scope-addressed Conversation actions and per-Session input registry. */ conversation: import('./service.ts').IConversation diff --git a/packages/client/ui-conversation/src/client/input/facade.ts b/packages/client/ui-conversation/src/client/input/facade.ts index 4f4d0aa300..77bff28708 100644 --- a/packages/client/ui-conversation/src/client/input/facade.ts +++ b/packages/client/ui-conversation/src/client/input/facade.ts @@ -5,8 +5,8 @@ * scoped-event application verbs, the submit transaction plumbing * (adjudicate via the session's InputTriggerController; claim.submit; default * sink), the notice channel, and the draft persistence mirror. - * Package-private; the hub alone constructs it and wires the scoped event - * listeners onto it. + * Package-private; InputHub binds Session events, while FirstDraft owns the + * local editor used before a Session exists. */ import type { Context } from '@deepseek-ai/cordis' import type { InboxState } from '@deepseek-ai/dsh-agent/types' diff --git a/packages/client/ui-conversation/src/client/input/first-draft.ts b/packages/client/ui-conversation/src/client/input/first-draft.ts new file mode 100644 index 0000000000..9e1c486eae --- /dev/null +++ b/packages/client/ui-conversation/src/client/input/first-draft.ts @@ -0,0 +1,79 @@ +/** Local text draft retained until the first Workspace and Session can accept it. */ +import type { Context } from '@deepseek-ai/cordis' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { FirstDraftState, SubmitOutcome } from '../contract/input.ts' +import type { InputSubmitMode } from '../contract/composer-submission.ts' +import { SessionInputShell } from './facade.ts' + +/** First-use navigation and the resident destination input. */ +interface FirstDraftDeps { + open(beforeOpen: (id: SessionId) => void, signal: AbortSignal): Promise + shell(id: SessionId): SessionInputShell +} + +/** Owns a root-lifetime text editor without allocating a Host Session. */ +export class FirstDraft { + /** Preparation progress and the recoverable directory failure. */ + readonly state = createSnapshotStore({ busy: false, failed: false }) + /** Local editor that stays independent of Host Session allocation. */ + readonly shell: SessionInputShell + private pending: { text: string; transferred: boolean } | undefined + + /** @param ctx - Client plugin lifetime. @param deps - Workspace navigation and Session input access. */ + constructor(private readonly ctx: Context, private readonly deps: FirstDraftDeps) { + this.shell = new SessionInputShell({ + actx: ctx, + defaultSink: (text, _attachments, mode, signal) => this.send(text, mode, signal), + commandAttachments: { + serialize: () => Promise.resolve([]), + release: () => {}, + unsupportedNotice: () => '', + }, + }) + ctx.effect(() => () => { this.shell.dispose() }, 'conversation.input: first-use draft') + } + + /** Dismiss the preparation failure while retaining the draft. */ + dismiss(): void { + this.state.set({ ...this.state.getSnapshot(), failed: false }) + } + + /** + * Move the unsent text to a selected Session. + * @param id - retained destination Session receiving the unsent text. + */ + transfer(id: SessionId): void { + const text = this.pending?.text ?? this.shell.snapshot.draft + if (text !== '') this.deps.shell(id).setDraft(text) + if (this.pending !== undefined) this.pending.transferred = true + this.shell.setDraft('') + this.dismiss() + } + + private async send(text: string, mode: InputSubmitMode, signal: AbortSignal): Promise { + if (this.pending !== undefined) return { kind: 'error' } + const pending = { text, transferred: false } + this.pending = pending + this.state.set({ busy: true, failed: false }) + let target: SessionInputShell | undefined + try { + const id = await this.deps.open((nextId) => { this.transfer(nextId) }, signal) + if (id === undefined) return { kind: pending.transferred ? 'success' : 'error' } + target = this.deps.shell(id) + await this.ctx.serial('conversation/prepare-first-send', id) + signal.throwIfAborted() + target.submit(mode) + return { kind: 'success' } + } catch (error) { + if (!signal.aborted) { + if (target !== undefined) target.notify('error', error instanceof Error ? error.message : String(error)) + else if (!pending.transferred) this.state.set({ busy: true, failed: true }) + } + return { kind: pending.transferred ? 'success' : 'error' } + } finally { + this.pending = undefined + this.state.set({ ...this.state.getSnapshot(), busy: false }) + } + } +} diff --git a/packages/client/ui-conversation/src/client/locales.ts b/packages/client/ui-conversation/src/client/locales.ts index 464ff55e17..c66fe10a8a 100644 --- a/packages/client/ui-conversation/src/client/locales.ts +++ b/packages/client/ui-conversation/src/client/locales.ts @@ -9,6 +9,10 @@ const PLAN_NEXT_ACTION_EN = 'describe your task to generate plan' /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { + 'defaultWorkspace.failed': '无法创建默认工作区', + 'defaultWorkspace.title': '默认工作区', + 'defaultWorkspace.retry': '请选择一个文件夹后重试', + 'defaultWorkspace.choose': '选择文件夹', 'hint.plan': PLAN_NEXT_ACTION_ZH, 'hint.goal': '输入目标,智能体将持续执行', 'hint.goal.active': '当前目标进行中。可输入 edit 修改 / pause 暂停 / resume 继续 / clear 清除', @@ -360,6 +364,10 @@ export type ConversationKey = keyof typeof zh /** English dictionary, checked complete against the zh key set. */ export const en = { + 'defaultWorkspace.failed': 'Unable to create default workspace', + 'defaultWorkspace.title': 'Default workspace', + 'defaultWorkspace.retry': 'Please choose a folder and try again', + 'defaultWorkspace.choose': 'Choose folder', 'hint.plan': PLAN_NEXT_ACTION_EN, 'hint.goal': 'describe the objective for a long-running task', 'hint.goal.active': 'goal active — edit / pause / resume / clear', diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx index adace1c113..bf6456291f 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx @@ -1,5 +1,6 @@ import { useCallback, useEffect, useRef, useState } from 'react' import clsx from 'clsx' +import { Button, Modal } from '@deepseek-ai/dsh-client-ui-primitives' import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types' import type { ConversationContentProps, ConversationViewsProps, InputZone } from '../contract/slots.ts' import { HeroShell, WorkspaceChip, workspaceLabel } from './EmptyHero.tsx' @@ -22,7 +23,7 @@ export function ConversationContent(props: ConversationContentProps) { const { sessionId, phase, hero, useSession, useSessions, useSessionStatus, useWorkspaces, useInput, useComposerBlock, renderSlot, renderSlotChain, - selectWorkspace, t, useFactorySlot, + selectWorkspace, dismissDefaultFailure, useFirstDraft, t, useFactorySlot, } = props const session = useSession(snapshot => snapshot) const Views = useFactorySlot('views', ConversationSessionView) @@ -33,6 +34,8 @@ export function ConversationContent(props: ConversationContentProps) { const inputState = useInput(s => s) const cwd = useSessions(s => sessionId === undefined ? undefined : s.byId[sessionId]?.cwd) const workspaces = useWorkspaces(s => s) + const sessionsReady = useSessions(s => s.phase === 'ready') + const firstDraft = useFirstDraft(s => s) // A plugin this package cannot import (ui-model-selection) says this session cannot // send; its reason is already localized by whoever raised it. const composerBlock = useComposerBlock(block => block) @@ -127,15 +130,13 @@ export function ConversationContent(props: ConversationContentProps) { ) - // The placeholder chip ("Choose workspace") and the Workspace-trigger input travel - // together: no workspace picked yet (cold start, no session at all), or a - // blank session whose workspace vanished (deleted from the sidebar). The - // bar is ONE session-maybe slot rendered unconditionally — inert is a prop, - // not a different tree, so the textarea DOM survives the transition. - const inert = sessionId === undefined || (hero && chipTitle === undefined) - // A raised block is the same inert posture with the blocker's own reason: - // one disabled textarea, never a second tree. The no-workspace state wins - // when both hold — picking a workspace is the earlier prerequisite. + // First-use sending waits for both baselines. A blank Session whose + // Workspace disappeared still requires explicit directory selection. + const needsWorkspace = sessionId !== undefined && hero && chipTitle === undefined + const inert = firstDraft.busy || (sessionId === undefined + ? workspaces.phase !== 'ready' || !sessionsReady + : needsWorkspace) + // Owner availability takes precedence over a Session-specific model block. const blocked = !inert && composerBlock !== undefined const inputBar = renderSlot('conversation.composer.bar', { variant: hero ? 'hero' : 'composer', @@ -144,7 +145,7 @@ export function ConversationContent(props: ConversationContentProps) { disabled: true, placeholder: t('placeholder.workspace'), workspacePickerOpen: pickerOpen, - onRequestWorkspace: () => { setPickerOpen(true) }, + ...(needsWorkspace ? { onRequestWorkspace: () => { setPickerOpen(true) } } : {}), } : blocked // `blocked`, not `disabled`: the bar refuses input either way, but a @@ -191,6 +192,23 @@ export function ConversationContent(props: ConversationContentProps) { {composerSeat} + + + + + )} + > + {t('defaultWorkspace.retry')} + ) } diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.tsx index c57fe69936..f66ee7a96a 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.tsx @@ -1,6 +1,5 @@ -// Resident conversation skeleton. Hero chrome, composer positioning, the -// chain, AND the composer bar (session-maybe slot) stay mounted across -// no-session/session transitions — the bar renders inert via owner props. +// Resident conversation shell keeps the composer mounted across local-draft, +// blank-Session, and active-conversation views. import type { ConversationSlotProps } from '../contract/slots.ts' import { ConversationMainPanel } from './ConversationMainPanel.tsx' diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx index 6a4ea12740..5852e4b5c4 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx @@ -1,16 +1,12 @@ /** The default composer body: the 'conversation.composer.bar' slot entry. - * Machine state arrives through the standard provide channel - * (useInput + inputActions); the keyboard/DOM command face and stop arrive - * through this entry's own inject, whose hooks compartment binds - * useNotices/useLexicon; layout-phase inputs (variant and placeholder) ride - * the owner props. Session facts - * (running/removed/promptError) are self-selected via useSession. + * The injected input state and keyboard address the current Session or the + * first-use local draft. Standard Session props supply attachment actions; + * owner props control layout and availability. * * The text surface is the shell-owned Lexical editor bound here through * ComposerContentEditable; chips render as decorator portals, and the * keymap registers submit/menu/paste gestures on the editor command layer. - * The no-session state renders the SAME div inert as the Workspace-picker - * trigger instead of a parallel tree. + * The contenteditable remains mounted when the first Session arrives. */ import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react' @@ -42,7 +38,7 @@ import css from './InputBar.module.css' export type InputBarProps = ComposerBarProps export const InputBar = memo(function InputBar({ - useSession, useInput, inputActions, keyboard, addFiles, removeAttachment, resolveDraftAttachments, + useSession, useComposerInput, inputActions, keyboard, addFiles, removeAttachment, resolveDraftAttachments, retryFileUpload, toggleCommandMenu, stop, t, renderSlot, useBusyEnter, useFileUploads, useNotices, useLexicon, useMenuLauncher, @@ -50,7 +46,7 @@ export const InputBar = memo(function InputBar({ workspacePickerOpen = false, onRequestWorkspace, placeholder, accessory, }: InputBarProps) { - const input = useInput(s => s) + const input = useComposerInput(s => s) const notice = useNotices(s => s) const busyEnter = useBusyEnter(s => s) void useLexicon // hook seat stays bound by the inject compartment; text-ref decoration rides the shell's editor transforms @@ -64,14 +60,11 @@ export const InputBar = memo(function InputBar({ const planActive = useProjection('plan', plan => plan !== undefined && (plan.pending ? !plan.active : plan.active)) // Absent (undefined: no frame yet) and cleared (null) both mean no goal. const hasGoal = useProjection('goal', goal => goal != null) - // Session-maybe: the machine faces are absent together while no session is - // current; the bar renders the same DOM inert instead of a parallel tree. - const live = input !== undefined && keyboard !== undefined && inputActions !== undefined - const draft = input?.draft ?? '' - const editor = keyboard?.editor ?? null + const draft = input.draft + const editor = keyboard.editor const attachments = useMemo( - () => input === undefined || resolveDraftAttachments === undefined ? [] : resolveDraftAttachments(input.attachmentIds), - [resolveDraftAttachments, input?.attachmentIds], + () => resolveDraftAttachments === undefined ? [] : resolveDraftAttachments(input.attachmentIds), + [resolveDraftAttachments, input.attachmentIds], ) const empty = draft.trim() === '' && attachments.length === 0 const uploads = useFileUploads(snapshot => snapshot) @@ -93,8 +86,7 @@ export const InputBar = memo(function InputBar({ // The deployment's image-intake limits (absent while no attachment service // is composed — the pre-check below then defers entirely to the host). const imageLimits = useProjection('imageLimits') - // Prompt failures are ordinary failures (no create/attach transaction exists - // anymore): the toast announces promptError, the draft stays in the machine, + // The toast announces promptError, the draft stays in the machine, // and the user resubmits. A remount over a session whose machine still holds // an unresolved promptError deliberately re-announces it once — the failure // is still pending, and a transient banner is its only surface. Attachment @@ -122,35 +114,30 @@ export const InputBar = memo(function InputBar({ // but its independent Stop below stays available while it runs. const continuable = subagent?.address.mode === 'continuable' const parentOffline = continuable && subagent.parentAvailable !== true - // Running input stays free; locked = session removed, the - // inert no-workspace state, the machine faces absent (no session), or a - // parent-offline continuable child. An owner block also disables input; - // adjudicating and submitting render read-only so the draft stays visible. - const disabled = removed || inert || !live || blocked !== undefined || parentOffline + // Preparation, removed Sessions, and unavailable parents lock editing. + // Adjudicating and submitting keep the draft visible and read-only. + const disabled = removed || inert || blocked !== undefined || parentOffline const locked = disabled // The model seat is the ONE control a block leaves live: every block this // contract has is cleared by choosing a model, so locking it too would leave // the composer asking for the only thing it prevents. The other reasons to // be disabled do lock it — there is no session to choose a model for. - const modelSeatLocked = removed || inert || !live - const machineBusy = input?.phase === 'adjudicating' || input?.phase === 'submitting' - // The no-workspace surface remains the resident DOM node but acts as the - // existing picker trigger. Message controls stay locked until a Session - // exists; the trigger itself is read-only rather than disabled so pointer - // and keyboard users can reach the recovery action. + const modelSeatLocked = removed || inert + const machineBusy = input.phase === 'adjudicating' || input.phase === 'submitting' + // A blank Session whose Workspace was deleted offers directory selection + // through the same resident input node. const workspaceTrigger = inert && !removed && onRequestWorkspace !== undefined const editorDisabled = removed || (locked && !workspaceTrigger) - const editable = live && !locked && !machineBusy + const editable = !locked && !machineBusy const steeringAvailable = subagent === null || subagent.address.mode === 'continuable' const canSteerQueue = !locked && !machineBusy && !commandMenuOpen && empty && running && steeringAvailable && input.queue.length > 0 useEffect(() => { - if (input === undefined || inputActions === undefined) return - if (attachments.length !== input.attachmentIds.length) { + if (inputActions !== undefined && attachments.length !== input.attachmentIds.length) { inputActions.pruneAttachments(attachments.map(attachment => attachment.id)) } - }, [attachments, input?.attachmentIds, inputActions]) + }, [attachments, input.attachmentIds, inputActions]) // Scroll the draft scrollport the minimum that brings the selection focus // into view — the browser's own behavior for typing, performed for the @@ -167,7 +154,7 @@ export const InputBar = memo(function InputBar({ // is ours to perform — switching to a longer draft otherwise leaves the // caret (restored at the draft's end) off screen. useEffect(() => { - if (locked || editor === null) return + if (locked) return focusDraftEditor(editor, revealSelection) }, [locked, sessionId, editor]) @@ -244,12 +231,10 @@ export const InputBar = memo(function InputBar({ } useEffect(() => { - if (keyboard === undefined) return return installDraftFilePicker(keyboard, gate, fileInputRef) }, [keyboard]) useEffect(() => { - if (editor === null || keyboard === undefined) return return installDraftKeymap(editor, keyboard, gate) }, [editor, keyboard]) @@ -262,17 +247,16 @@ export const InputBar = memo(function InputBar({ } const onToggleCommandMenu = (): void => { - if (keyboard === undefined) return // The menu is a combobox over the editor, so the keyboard has to be there // before the launcher opens it: activating the button from the keyboard // leaves focus on the button, and restoring it afterwards would re-track an // empty draft and close the menu again. - if (editor !== null) focusDraftEditor(editor, revealSelection) + focusDraftEditor(editor, revealSelection) toggleCommandMenu?.(keyboard.caretSpan()) } - // The no-session Workspace trigger: the resident editable div acts as the - // picker trigger for keyboard users (no editor is bound in this state). + // When a blank Session loses its Workspace, the resident editable div acts as the + // picker trigger for keyboard users. const onWorkspaceKeyDown = (e: KeyboardEvent): void => { if (!workspaceTrigger) return if (e.key === 'Enter' || e.key === ' ') { @@ -295,7 +279,7 @@ export const InputBar = memo(function InputBar({ const primaryDisabled = primaryStops ? stop === undefined : empty || disabled || machineBusy || uploadsPending const interruptible = running && continuable const primarySubmitMode = resolveSubmitMode(busyEnter, running, 'enter', steeringAvailable) - const plainMessageDraft = !empty && input?.phase === 'plain' && !draft.trimStart().startsWith('/') + const plainMessageDraft = !empty && input.phase === 'plain' && !draft.trimStart().startsWith('/') const primaryLabel = primaryStops ? t('input.stop') : running && steeringAvailable && !disabled && !uploadsPending && plainMessageDraft @@ -306,7 +290,6 @@ export const InputBar = memo(function InputBar({ stop?.() return } - if (keyboard === undefined) return // absent machine: the button is disabled /* v8 ignore next -- defensive: the primary button is disabled for empty, disabled, and pending-upload states. */ if (!empty && !disabled && !machineBusy && !uploadsPending) keyboard.submit(primarySubmitMode) } @@ -314,7 +297,7 @@ export const InputBar = memo(function InputBar({ // Claim ghost hint: rendered by CSS as generated content after the last // paragraph while the claim's args are blank (a hint implies a single-line // token draft). The translated per-command hint wins over the claim's own. - const claimActive = (input?.phase === 'claimed' || input?.phase === 'submitting') + const claimActive = (input.phase === 'claimed' || input.phase === 'submitting') && input.claim !== undefined && draft.startsWith(input.claim.token) const rawHint = claimActive && input.claim.hint !== undefined && draft.slice(input.claim.token.length).trim() === '' @@ -322,7 +305,7 @@ export const InputBar = memo(function InputBar({ : null const hint = ((): string | null => { if (rawHint === null) return null - const commandName = input?.claim?.name ?? '' + const commandName = input.claim?.name ?? '' const hintKey = `hint.${commandName === 'goal' && hasGoal ? 'goal.active' : commandName}` // Dynamic lookup by claimed command name: unknown commands miss the // dictionary and keep the machine's own hint, so the call is wide. @@ -396,7 +379,7 @@ export const InputBar = memo(function InputBar({ scrollRef={scrollRef} editable={editable} editorDisabled={editorDisabled} - phase={input?.phase ?? 'inert'} + phase={input.phase} placeholderText={placeholderText} ariaLabel={workspaceTrigger ? t('hero.chooseWorkspace') : placeholderText} workspaceTrigger={workspaceTrigger} @@ -433,12 +416,12 @@ export const InputBar = memo(function InputBar({ {sessionId === undefined ? null : renderSlot('conversation.input.permission', { locked })} {sessionId === undefined ? null : renderSlot('conversation.input.plan', { locked })} - {input === undefined || sessionId === undefined + {sessionId === undefined ? null : renderSlot('conversation.input.left', {})}
- {input === undefined || sessionId === undefined + {sessionId === undefined ? null : renderSlot('conversation.input.right', {})} {sessionId === undefined ? null : renderSlot('conversation.input.model', { locked: modelSeatLocked })} @@ -482,7 +465,7 @@ export const InputBar = memo(function InputBar({
- {variant === 'composer' && input !== undefined && sessionId !== undefined + {variant === 'composer' && sessionId !== undefined ? renderSlot('conversation.composer.dock', {}) : null} diff --git a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx index 6c12f28cfb..abc74918d5 100644 --- a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx @@ -2,6 +2,7 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { describe, expect, it, onTestFinished, vi } from 'vitest' import type { CommandContribution, CommandUiContract } from '@deepseek-ai/dsh-client-ui-commands/client' +import type { UiWorkspace } from '@deepseek-ai/dsh-client-ui-workspace/client' import type { ISession, SessionReference } from '@deepseek-ai/dsh-api-session-controller/client' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' @@ -73,12 +74,14 @@ async function bench() { opened(id) } const openSession = vi.fn((id: SessionId) => { replaceMain(id) }) + const openDefaultWorkspace = vi.fn(async () => undefined) runtime.ctx.provide('uiWorkspace', { openWorkspace: async (_workspaceId: WorkspaceId, beforeOpen: (id: SessionId) => void) => { const id = await connectWorkspace() replaceMain(id, beforeOpen) }, openSession, + openDefaultWorkspace, } as never) const sessionFake = sessionFakeFor() await runtime.sessions.add({ @@ -136,10 +139,54 @@ async function bench() { return { runtime, feature, slots: runtime.slots, entryOf, conversationApi, headerApi, residentApi, composerApi, inputApi, viewSource, sessionFake, connectWorkspace, rootUpload, uploads, rootReference, references, opened, + locale, openDefaultWorkspace, } } describe('Conversation inject API', () => { + it.each([ + ['zh', '默认工作区', '默认工作区'], + ['en', 'Default workspace', 'Default workspace'], + ['ja', 'default-workspace', 'Default workspace'], + ])('resolves first-use names in the Client using the send-time locale %s', async (language, directoryName, title) => { + const b = await bench() + if (language === 'ja') b.locale.addLanguage({ id: 'ja', label: '日本語', fallback: 'en' }) + const composer = b.composerApi(undefined) + composer.keyboard.paste('first message') + b.locale.setLocale(language) + composer.keyboard.submit('steer') + await vi.waitFor(() => { + expect(b.openDefaultWorkspace).toHaveBeenCalledWith({ directoryName, title }, expect.any(Function), expect.any(AbortSignal)) + expect(b.residentApi(undefined).hooks.firstDraft.getSnapshot().busy).toBe(false) + }) + }) + + it('keeps in-flight names fixed and resolves the new locale when retrying a failed first send', async () => { + const b = await bench() + const pending = Promise.withResolvers() + b.openDefaultWorkspace.mockReturnValueOnce(pending.promise) + const composer = b.composerApi(undefined) + b.locale.setLocale('en') + composer.keyboard.paste('keep this draft') + composer.keyboard.submit('steer') + try { + await vi.waitFor(() => { expect(b.openDefaultWorkspace).toHaveBeenCalledOnce() }) + b.locale.setLocale('zh') + expect(b.openDefaultWorkspace.mock.calls[0]?.[0]).toEqual({ directoryName: 'Default workspace', title: 'Default workspace' }) + pending.reject(new Error('directory unavailable')) + await vi.waitFor(() => { expect(b.residentApi(undefined).hooks.firstDraft.getSnapshot().busy).toBe(false) }) + expect(composer.hooks.composerInput.getSnapshot().draft).toBe('keep this draft') + composer.keyboard.submit('steer') + await vi.waitFor(() => { + expect(b.openDefaultWorkspace).toHaveBeenLastCalledWith({ directoryName: '默认工作区', title: '默认工作区' }, expect.any(Function), expect.any(AbortSignal)) + expect(b.residentApi(undefined).hooks.firstDraft.getSnapshot().busy).toBe(false) + }) + } finally { + pending.resolve(undefined) + await vi.waitFor(() => { expect(b.residentApi(undefined).hooks.firstDraft.getSnapshot().busy).toBe(false) }) + } + }) + it('owns the File action, reads its mounted composer availability, and unregisters on disposal', async () => { const b = await bench() onTestFinished(() => b.runtime.dispose()) @@ -159,7 +206,7 @@ describe('Conversation inject API', () => { expect(file.available({ sessionId: 'missing' as SessionId })).toBe(false) if (file.ui.kind !== 'action') throw new Error('File must be an action') file.ui.run({ sessionId: 'missing' as SessionId }) - const keyboard = b.composerApi(ROOT).keyboard! + const keyboard = b.composerApi(ROOT).keyboard const open = vi.fn() let available = true const unbind = keyboard.bindFilePicker({ open, available: () => available }) @@ -386,7 +433,8 @@ describe('Conversation inject API', () => { expect(() => { injectBar('ghost' as SessionId).stop!() }).toThrow(/resolved no binding/) const absent = injectBar(undefined) - expect(absent.keyboard).toBeUndefined() + expect(absent.keyboard).toBeDefined() + expect(absent.hooks.composerInput.getSnapshot().draft).toBe('') expect(absent.toggleCommandMenu).toBeUndefined() expect(absent.stop).toBeUndefined() expect(absent.hooks.notices.getSnapshot()).toBeNull() diff --git a/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx b/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx index 84e5ba28a1..51513cb28e 100644 --- a/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx +++ b/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx @@ -100,8 +100,10 @@ async function bench(opts?: { blank?: boolean }) { } describe('resident composer', () => { - it('renders the locked view state while no session exists at all', async () => { + it('accepts a local draft before any Session exists and keeps the Workspace chip available', async () => { const runtime = await SlotTestRuntime.create() + runtime.sessions.list.set({ ...runtime.sessions.list.getSnapshot(), phase: 'pending' }) + await runtime.workspaces.update((draft) => { draft.phase = 'pending' }) provideWorkspaceNavigation(runtime) runtime.ctx.provide('settingsScope', { developerTools: { enabled: createSnapshotStore(true) }, bind: () => stubSettingsScope().scope } as never) const locale = new LocaleRuntime(runtime.ctx) @@ -113,15 +115,21 @@ describe('resident composer', () => { const view = runtime.renderRoot() const textarea = view.container.querySelector('[data-composer-input]') expect(textarea).not.toBeNull() + expect(textarea!.getAttribute('contenteditable')).toBe('false') + await runtime.workspaces.update((draft) => { draft.phase = 'ready' }) + expect(textarea!.getAttribute('contenteditable')).toBe('false') + await act(async () => { + runtime.sessions.list.set({ ...runtime.sessions.list.getSnapshot(), phase: 'ready' }) + }) expect(textarea!.getAttribute('aria-disabled')).not.toBe('true') - expect(textarea!.getAttribute('contenteditable')).not.toBe('true') - expect(textarea!.getAttribute('aria-haspopup')).toBe('menu') + expect(textarea!.getAttribute('contenteditable')).toBe('true') + expect(textarea!.getAttribute('aria-haspopup')).toBeNull() expect(view.getByTestId('workspace-probe').textContent).toBe('false:0') - fireEvent.click(textarea!) - expect(view.getByTestId('workspace-probe').textContent).toBe('true:0') - expect(textarea!.getAttribute('aria-expanded')).toBe('true') fireEvent.click(view.getByRole('button', { name: '选择工作区' })) - fireEvent.keyDown(textarea!, { key: 'Enter' }) + expect(view.getByTestId('workspace-probe').textContent).toBe('true:0') + expect(textarea!.getAttribute('aria-expanded')).toBeNull() + fireEvent.click(view.getByRole('button', { name: '选择工作区' })) + fireEvent.click(view.getByRole('button', { name: '选择工作区' })) expect(view.getByTestId('workspace-probe').textContent).toBe('true:0') expect(view.getByRole('button', { name: '选择工作区' })).toBeTruthy() await runtime.dispose() @@ -149,7 +157,7 @@ describe('resident composer', () => { const workspaceChip = view.getByRole('button', { name: '选择工作区' }) const workspaceProbe = view.getByTestId('workspace-probe') expect(textarea.getAttribute('aria-disabled')).not.toBe('true') - expect(textarea.getAttribute('contenteditable')).not.toBe('true') + expect(textarea.getAttribute('contenteditable')).toBe('true') fireEvent.click(workspaceChip) fireEvent.click(workspaceProbe) diff --git a/packages/client/ui-conversation/tests/first-draft.client.spec.ts b/packages/client/ui-conversation/tests/first-draft.client.spec.ts new file mode 100644 index 0000000000..3d223a38fe --- /dev/null +++ b/packages/client/ui-conversation/tests/first-draft.client.spec.ts @@ -0,0 +1,141 @@ +import { Context } from '@deepseek-ai/cordis' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { SessionId } from '@deepseek-ai/dsh-session/types' +import { FirstDraft } from '../src/client/input/first-draft.ts' +import { SessionInputShell } from '../src/client/input/facade.ts' +import type { SubmitOutcome } from '../src/client/contract/input.ts' + +const contexts: Context[] = [] +afterEach(async () => { + for (const ctx of contexts.splice(0)) await ctx.fiber.dispose() +}) + +function harness() { + const ctx = new Context() + contexts.push(ctx) + const opened = Promise.withResolvers() + ctx.effect(() => () => { opened.resolve(undefined) }) + const submitted = vi.fn(async (): Promise => ({ kind: 'success' })) + const target = new SessionInputShell({ + actx: ctx, + defaultSink: submitted, + commandAttachments: { serialize: async () => [], release: () => {}, unsupportedNotice: () => '' }, + }) + ctx.effect(() => () => { target.dispose() }) + let beforeOpen: ((id: SessionId) => void) | undefined + const open = vi.fn((prepare: (id: SessionId) => void) => { + beforeOpen = prepare + return opened.promise + }) + const first = new FirstDraft(ctx, { open, shell: () => target }) + return { + ctx, first, target, submitted, open, opened, + complete: () => { + const id = SessionId('default') + beforeOpen!(id) + opened.resolve(id) + }, + } +} + +describe('first message draft', () => { + it('retains a local draft without opening a Session until send', async () => { + const h = harness() + h.first.shell.setDraft('first message') + expect(h.open).not.toHaveBeenCalled() + h.first.shell.submit('steer') + expect(h.open).toHaveBeenCalledTimes(1) + expect(h.first.state.getSnapshot().busy).toBe(true) + h.first.shell.submit('steer') + expect(h.open).toHaveBeenCalledTimes(1) + h.complete() + await vi.waitFor(() => { expect(h.submitted).toHaveBeenCalledTimes(1) }) + expect(h.submitted.mock.calls[0]).toEqual(['first message', [], 'steer', expect.any(AbortSignal)]) + expect(h.first.state.getSnapshot()).toEqual({ busy: false, failed: false }) + }) + + it.each([false, true])('waits for first-use settings and keeps the Session draft on refusal (refused: %s)', async (refused) => { + const h = harness() + const settings = Promise.withResolvers() + const started = Promise.withResolvers() + h.ctx.on('conversation/prepare-first-send', (id) => { + started.resolve(id) + return settings.promise + }) + try { + h.first.shell.setDraft('use my selected mode') + h.first.shell.submit() + h.complete() + expect(await started.promise).toBe(SessionId('default')) + expect(h.submitted).not.toHaveBeenCalled() + if (refused) settings.reject(new Error('preset refused')) + else settings.resolve(undefined) + await vi.waitFor(() => { expect(h.first.state.getSnapshot().busy).toBe(false) }) + expect(h.first.state.getSnapshot().failed).toBe(false) + if (refused) { + expect(h.submitted).not.toHaveBeenCalled() + expect(h.target.snapshot.draft).toBe('use my selected mode') + expect(h.target.notices.getSnapshot()?.text).toBe('preset refused') + } else { + expect(h.submitted).toHaveBeenCalledOnce() + } + } finally { + settings.resolve(undefined) + await vi.waitFor(() => { expect(h.first.state.getSnapshot().busy).toBe(false) }) + } + }) + + it('restores input on preparation failure and dismisses the modal without losing it', async () => { + const h = harness() + h.first.shell.setDraft('preserve me') + h.first.shell.submit() + h.opened.reject(new Error('permission denied')) + await vi.waitFor(() => { expect(h.first.shell.snapshot.draft).toBe('preserve me') }) + expect(h.first.state.getSnapshot()).toEqual({ busy: false, failed: true }) + expect(h.submitted).not.toHaveBeenCalled() + h.first.dismiss() + expect(h.first.state.getSnapshot().failed).toBe(false) + expect(h.first.shell.snapshot.draft).toBe('preserve me') + }) + + it('hands a draft to a manual selection without sending it', async () => { + const h = harness() + h.first.shell.setDraft('manual folder') + h.first.transfer(SessionId('manual')) + expect(h.target.snapshot.draft).toBe('manual folder') + expect(h.first.shell.snapshot.draft).toBe('') + expect(h.submitted).not.toHaveBeenCalled() + }) + + it('lets manual navigation take the pending draft and cancels automatic submission', async () => { + const h = harness() + h.first.shell.setDraft('pending text') + h.first.shell.submit() + h.first.transfer(SessionId('manual')) + h.opened.resolve(undefined) + await vi.waitFor(() => { expect(h.first.state.getSnapshot().busy).toBe(false) }) + expect(h.target.snapshot.draft).toBe('pending text') + expect(h.first.shell.snapshot.draft).toBe('') + expect(h.submitted).not.toHaveBeenCalled() + }) + + it('restores a superseded draft without a directory error', async () => { + const h = harness() + h.first.shell.setDraft('later') + h.first.shell.submit() + h.opened.resolve(undefined) + await vi.waitFor(() => { expect(h.first.shell.snapshot.draft).toBe('later') }) + expect(h.first.state.getSnapshot().failed).toBe(false) + }) + + it('leaves ordinary send failures in the selected Session input', async () => { + const h = harness() + h.submitted.mockResolvedValue({ kind: 'error' }) + h.first.shell.setDraft('retry the prompt') + h.first.shell.submit() + h.complete() + await vi.waitFor(() => { expect(h.target.snapshot.draft).toBe('retry the prompt') }) + expect(h.first.shell.snapshot.draft).toBe('') + expect(h.first.state.getSnapshot().failed).toBe(false) + }) +}) diff --git a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx index 9e0366952c..a4805db1ec 100644 --- a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx @@ -185,6 +185,7 @@ function bench(over?: BenchOptions) { ? over?.plan : key === 'goal' ? over?.goal : key === 'imageLimits' ? over?.imageLimits : undefined)), + useComposerInput: bindSnapshotSelector(shell.state), useInput: bindSnapshotSelector(shell.state), inputActions: shell.actions, keyboard: shell, diff --git a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx index 15d87a0ca7..c8641afcb4 100644 --- a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx @@ -67,6 +67,7 @@ function mountBar(shell: SessionInputShell, over?: { running?: boolean; disabled })), useProjection: (() => undefined), useConversation: bindSnapshotSelector(createSnapshotStore(conversationSnapshot())), + useComposerInput: bindSnapshotSelector(shell.state), useInput: bindSnapshotSelector(shell.state), inputActions: shell.actions, keyboard: shell, diff --git a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx index 347b4d05c1..0c098d95fb 100644 --- a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx @@ -161,6 +161,7 @@ async function scopedBench(register?: (inputTriggers: InputTriggerService) => vo })), useProjection: (() => undefined), useConversation: bindSnapshotSelector(createSnapshotStore(conversationSnapshot())), + useComposerInput: bindSnapshotSelector(shell.state), useInput: bindSnapshotSelector(shell.state), inputActions: shell.actions, keyboard: shell, diff --git a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx index 17aadfb056..25f7002ea4 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -137,6 +137,8 @@ function mount( nestedSubagent?: boolean /** A composer block another plugin raised for this session. */ composerBlock?: { reason: string } + /** First-use preparation remains active after selecting its Session. */ + preparingFirstDraft?: boolean /** Mutable view ledger used by registration-order regressions. */ viewTabs?: ViewTab[] } = {}, @@ -280,6 +282,7 @@ function mount( useProjection={(() => undefined)} useInput={useInput} inputActions={inputActions} + useComposerInput={useInput} keyboard={wiring} addFiles={() => null} useFileUploads={bindSnapshotSelector(createSnapshotStore({}))} @@ -336,6 +339,8 @@ function mount( useWorkspaces: bindSnapshotSelector(workspaces), useProjection: (() => undefined), useComposerBlock: select => select(options.composerBlock), + useFirstDraft: select => select({ busy: options.preparingFirstDraft === true, failed: false }), + dismissDefaultFailure: () => {}, useInput, inputActions, renderSlot, @@ -405,6 +410,17 @@ describe('ConversationRoot resident composer', () => { expect(b.view.queryByTestId('view-conversation.session.header.corner')).toBeNull() }) + it('locks the selected Session draft until automatic first-use preparation settles', () => { + const b = mount(sessionSnapshotOf({ blank: true }), undefined, undefined, { + summaryBlank: true, preparingFirstDraft: true, + }) + const box = b.view.getByRole('textbox') + expect(box.getAttribute('aria-disabled')).toBe('true') + expect(box.getAttribute('aria-haspopup')).toBeNull() + fireEvent.keyDown(box, { key: 'Enter' }) + expect(b.sink).not.toHaveBeenCalled() + }) + it('does not redispatch composer child slots for an unrelated Session publication', () => { const b = mount(sessionSnapshotOf()) const childKeys = new Set([ diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index 5f4245e471..951fd978ab 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-workspace/README.md -README.md: 0125f563e7d0f062dd37f58a218d76dd85b0fa51 -README.zh.md: 9db3ea3a39f7c314ebb7d874d858457f00501bd7 +README.md: 6b34c9bf764d04df591317a22c55a47c2307459d +README.zh.md: 550490a49651d01e20537cb924a43112a233966c diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index 0125f563e7..6b34c9bf76 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -69,6 +69,8 @@ The value is intentionally best effort for cold Sessions. An identity-matching u New Session tries to acquire the first eligible blank in catalog order; startup restoration tries the saved blank. If that writer is held, navigation creates a new Session without trying other blanks. Other acquisition failures abort the request and are currently reported only to the console. Released blanks retain their slash-command state when reused. Later navigation cancels a pending startup selection. +`openDefaultWorkspace(request, beforeOpen, signal)` initializes the Host default Workspace from the requested directory name and title before connecting its Session. It captures navigation cancellation before directory preparation; superseded work cannot transfer the draft or select its Session. A successfully registered Workspace remains available when Session creation or later submission fails. [Conversation](../ui-conversation/README.md) owns the first-use draft and failure dialog. + ## Understand the implementation diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index 9db3ea3a39..550490a496 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -69,6 +69,8 @@ Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示** 新建会话尝试获取列表中第一个符合条件的空白会话;启动恢复尝试已保存的空白会话。若该写锁被占用,导航直接新建 Session,不再尝试其他空白会话。其他获取错误会中止请求,目前只报告到控制台。已释放的空白会话被复用时保留 slash 命令状态。后续导航会取消尚未完成的启动选择。 +`openDefaultWorkspace(request, beforeOpen, signal)` 在连接 Session 前,按请求中的目录名和标题初始化 Host 默认工作区。它在目录准备之前捕获导航取消信号;被取代的操作不能转移草稿或选中 Session。登记成功的工作区在 Session 创建或后续提交失败时仍然保留。[Conversation](../ui-conversation/README.zh.md) 负责首次使用草稿和失败弹窗。 + ## 理解实现 diff --git a/packages/client/ui-workspace/src/client/navigation.ts b/packages/client/ui-workspace/src/client/navigation.ts index 22138ec707..e6ccd65f62 100644 --- a/packages/client/ui-workspace/src/client/navigation.ts +++ b/packages/client/ui-workspace/src/client/navigation.ts @@ -12,7 +12,7 @@ import type { import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import type { - IWorkspaces, WorkspaceId, WorkspaceSnapshot, WorkspaceView, + IWorkspaces, WorkspaceId, WorkspaceInitializeDefaultRequest, WorkspaceSnapshot, WorkspaceView, } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' @@ -36,6 +36,18 @@ export interface UiWorkspace { * @returns completion; a superseded request may create a Session but does not open it. */ openWorkspace(workspaceId: WorkspaceId, beforeOpen?: (sessionId: SessionId) => void): Promise + /** + * Prepare the first-use Workspace and select its blank Session. + * @param request - initial directory name and title. + * @param beforeOpen - synchronous draft transfer after retaining the Session. + * @param signal - caller cancellation. + * @returns selected Session, or undefined after navigation supersession. + */ + openDefaultWorkspace( + request: WorkspaceInitializeDefaultRequest, + beforeOpen: (sessionId: SessionId) => void, + signal: AbortSignal, + ): Promise /** * Fork a Session without changing the current selection. * @param sessionId - source Session. @@ -184,6 +196,25 @@ class UiWorkspaceService extends Service implements UiWorkspace { this.replaceMain(sessionId, navigation, 'reveal', beforeOpen) } + async openDefaultWorkspace( + request: WorkspaceInitializeDefaultRequest, + beforeOpen: (sessionId: SessionId) => void, + signal: AbortSignal, + ): Promise { + const navigation = AbortSignal.any([this.ctx.layout.beginNavigation(), this.lifetime.signal, signal]) + try { + const workspace = await this.workspaces.initializeDefault(request, navigation) + navigation.throwIfAborted() + const sessionId = await this.connectWorkspace(workspace.workspaceId) + navigation.throwIfAborted() + this.replaceMain(sessionId, navigation, 'reveal', beforeOpen) + return sessionId + } catch (error) { + if (navigation.aborted) return undefined + throw error + } + } + async forkSession(sessionId: SessionId): Promise { await this.sessions.fork({ sessionId, increaseTitle: true }) } diff --git a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts index 310bb3627d..a952cb9d32 100644 --- a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts +++ b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts @@ -167,6 +167,11 @@ class FakeSessions implements ISessions { } class FakeWorkspaces implements IWorkspaces { + readonly initializeDefault = vi.fn(async () => { + const item = workspace('default') + this.list.set(workspaceState([item])) + return item + }) readonly list: MutableSource readonly archiveCalls: SessionId[] = [] readonly unarchiveCalls: SessionId[] = [] @@ -272,6 +277,41 @@ function bench(options: BenchOptions = {}) { } describe('UiWorkspaceService', () => { + it('prepares the default Workspace before creating and retaining its Session', async () => { + const b = bench({ workspaces: workspaceState(), sessions: sessionState() }) + const beforeOpen = vi.fn(() => { + expect(b.sessions.retain).toHaveBeenCalledWith(sid('created-default'), { source: 'mainView' }) + }) + await expect(b.uiWorkspace.openDefaultWorkspace({ directoryName: '默认工作区', title: '默认工作区' }, beforeOpen, new AbortController().signal)) + .resolves.toBe(sid('created-default')) + expect(b.workspaces.initializeDefault).toHaveBeenCalledWith({ directoryName: '默认工作区', title: '默认工作区' }, expect.any(AbortSignal)) + expect(b.sessions.create).toHaveBeenCalledWith({ workspaceId: wid('default') }) + expect(beforeOpen).toHaveBeenCalledWith(sid('created-default')) + }) + + it('does not create a Session when default preparation fails or is superseded', async () => { + const b = bench({ workspaces: workspaceState(), sessions: sessionState() }) + b.workspaces.initializeDefault.mockRejectedValueOnce(new Error('denied')) + await expect(b.uiWorkspace.openDefaultWorkspace({ directoryName: 'Default workspace', title: 'Default workspace' }, vi.fn(), new AbortController().signal)).rejects.toThrow('denied') + expect(b.sessions.create).not.toHaveBeenCalled() + const pending = Promise.withResolvers() + b.workspaces.initializeDefault.mockReturnValueOnce(pending.promise) + const beforeOpen = vi.fn() + const opening = b.uiWorkspace.openDefaultWorkspace({ directoryName: 'Default workspace', title: 'Default workspace' }, beforeOpen, new AbortController().signal) + b.uiWorkspace.openSession(sid('manual')) + pending.resolve(workspace('default')) + await expect(opening).resolves.toBeUndefined() + expect(b.sessions.create).not.toHaveBeenCalled() + expect(beforeOpen).not.toHaveBeenCalled() + }) + + it('retains the prepared Workspace if creating its Session fails', async () => { + const b = bench({ workspaces: workspaceState(), sessions: sessionState() }) + b.sessions.create.mockRejectedValueOnce(new Error('session failed')) + await expect(b.uiWorkspace.openDefaultWorkspace({ directoryName: 'Default workspace', title: 'Default workspace' }, vi.fn(), new AbortController().signal)).rejects.toThrow('session failed') + expect(b.workspaces.list.getSnapshot().items).toEqual([workspace('default')]) + }) + it('retains an explicit main target before revealing its Conversation', () => { const b = bench() b.uiWorkspace.openSession(sid('target')) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 78975d4a43..407b489580 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -3250,6 +3250,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'request', description: 'directory path to register.' }], returns: 'the Workspace and whether this call created it.', }, + { + signature: '@Remote(\'initializeDefault\') async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise', + description: 'Initialize or reuse the default Workspace before the first user message.', + parameters: [{ name: 'request', description: 'initial directory name and title; never rename an existing default.' }, { name: 'signal', description: 'caller lifetime; cancels native directory lookup.' }], + returns: 'the durable Workspace without creating a Session or sending a message.', + }, { signature: '@Remote(\'rename\') rename(request: WorkspaceRenameRequest): Promise', description: 'Rename one Workspace to a unique non-blank title.', @@ -3367,6 +3373,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'path', description: 'Existing directory to own, in a fully qualified path spelling.' }, { name: 'title', description: 'Display title used only when a new record is created.' }], returns: 'the existing or newly durable workspace.', }, + { + signature: 'initializeDefault(resolveDirectory: () => Promise<{ path: string; title: string }>): Promise', + description: 'Initialize the default Workspace only while both the registry and Session history are empty. Repeated requests reuse its durable identity; deleting that registration permanently disables automatic creation.', + parameters: [{ name: 'resolveDirectory', description: 'resolve the absolute directory and initial title; called only for eligible creation, inside the registry mutation queue. Missing directories are created recursively before registration.' }], + returns: 'the initialized Workspace, or undefined when automatic creation is ineligible.', + }, { signature: 'get(id: WorkspaceId): Workspace | undefined', description: 'Look up a workspace by id.', @@ -7279,6 +7291,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'WorkspaceFollowIncrement', declaration: 'export type WorkspaceFollowIncrement = {\n readonly type: \'upsert\';\n readonly workspace: WorkspaceView;\n} | {\n readonly type: \'remove\';\n readonly workspaceId: WorkspaceId;\n} | {\n readonly type: \'order\';\n readonly workspaceIds: readonly WorkspaceId[];\n} | {\n readonly type: \'archived\';\n readonly archivedSessionIds: readonly SessionId[];\n} | {\n readonly type: \'pinned\';\n readonly pinnedSessionIds: readonly SessionId[];\n};', }, + { + name: 'WorkspaceInitializeDefaultRequest', + declaration: 'export interface WorkspaceInitializeDefaultRequest {\n readonly directoryName: string;\n readonly title: string;\n}', + }, { name: 'WorkspaceInsertBeforeRequest', declaration: 'export interface WorkspaceInsertBeforeRequest {\n readonly workspaceId: WorkspaceId;\n readonly beforeWorkspaceId?: WorkspaceId;\n}', diff --git a/packages/test-support/client-runtime/src/workspaces.ts b/packages/test-support/client-runtime/src/workspaces.ts index 68a5c61d09..2c6b788fa3 100644 --- a/packages/test-support/client-runtime/src/workspaces.ts +++ b/packages/test-support/client-runtime/src/workspaces.ts @@ -1,7 +1,7 @@ /** Test-owned workspaces face: the renderer standard-kit observable plus recorded actions. */ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { - IWorkspaces, WorkspaceId, WorkspaceSnapshot, WorkspaceView, + IWorkspaces, WorkspaceId, WorkspaceInitializeDefaultRequest, WorkspaceSnapshot, WorkspaceView, } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { SnapshotStore } from '@deepseek-ai/dsh-client-store' @@ -80,6 +80,19 @@ export class TestWorkspaces implements IWorkspaces { } as unknown as WorkspaceView } + /** + * Initialize the default Workspace through an explicitly installed test stub. + * @param request - initial directory name and title. + * @param signal - caller lifetime. + * @returns the stubbed Workspace. + */ + async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise { + this.calls.push({ method: 'initializeDefault', args: [request, signal] }) + const stub = this.stubs.get('initializeDefault') + if (stub === undefined) throw new Error('initializeDefault requires a Workspace fixture') + return await (stub(request, signal) as Promise) + } + /** * Rename a Workspace (recorded). The default echoes a minimal view. * @param workspaceId - target workspace. diff --git a/packages/workspace/workspace/README.i18n.yaml b/packages/workspace/workspace/README.i18n.yaml index da38092a17..43e9c7d159 100644 --- a/packages/workspace/workspace/README.i18n.yaml +++ b/packages/workspace/workspace/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/workspace/workspace/README.md -README.md: 51fa66d346ffc4027397d8851b0c81ea87269ded -README.zh.md: 102308d3257ba13d3ec851adcbdb1d4c159abc14 +README.md: f11d6496c04cf346c21f869e00ec5fb5526008db +README.zh.md: 3d458e13157bda612c3d33d0e7bfb57fa914e9b3 diff --git a/packages/workspace/workspace/README.md b/packages/workspace/workspace/README.md index 51fa66d346..f11d6496c0 100644 --- a/packages/workspace/workspace/README.md +++ b/packages/workspace/workspace/README.md @@ -33,7 +33,7 @@ Use it when the product shows a persistent workspace surface — a sidebar, sess ### Setting up -The package takes no configuration of its own; it needs a session store, a session persistence backend, and the storage rows that keep its records. A minimal composition: +The package needs a session store, a session persistence backend, and the storage rows that keep its records. A minimal composition: ```yaml - name: '@deepseek-ai/dsh-session' @@ -59,6 +59,15 @@ await project.setTitle('Renamed') ctx.workspaceRegistry.list() // shows the project, newest first ``` + +### First-use Workspace + +`initializeDefault(resolveDirectory)` initializes the default Workspace without creating a Session. Initial creation requires an empty Workspace registry and no live, persisted, or archived Session, including Sessions without a working directory. The registry checks persistent history directly; an empty visible sidebar is insufficient. + +The directory resolver runs inside the mutation queue only when creation is eligible. It returns an absolute path and initial title; the registry creates missing parent directories, canonicalizes the path, rechecks Session history, and commits the Workspace with its initialization marker. An existing directory is reused; a file conflict or directory failure rejects initialization. The [Host controller](../../api/workspace-controller/README.md#first-use-workspace) supplies the Documents path policy. + +The first successful registration records its identity durably. Repeated calls return it without resolving a directory again; renaming keeps that identity, and deleting its registration does not permit another automatic creation. Directory or registration failure leaves initialization unset for retry. Directories created before a later failure remain on disk. The [first-use decision](../../../.agents/notes/implemented/feature/2026-09-20-default-workspace.md) explains this lifetime. + ### Grouping sessions under a project A session joins the project of the directory it runs in: create a session in a project's directory and it appears under that project, newest first. A session can only belong to one project. A session whose directory cannot be validated — no recorded directory, or a moved or deleted folder — cannot join and stays ungrouped. @@ -102,7 +111,7 @@ The API has two owners: `WorkspaceRegistry` creates, orders, and deletes project ### Durable shape -The registry opens the `workspace` domain (version 2): a `workspaces` table keyed by `WorkspaceId` plus one global state holding `workspaceIds` (the authoritative display order), `archivedSessionIds`, `pinnedSessionIds`, and the optional `pendingMutation` marker. Archive and pin sets contain Session id strings, default to empty, and carry no per-entry objects or timestamps; the pin array keeps the most recently pinned id first. Archiving clears the pin in the same global-state write without changing Workspace membership. Unarchive runs no session-existence probe, because dropping an id from the set cannot introduce an unknown one, while archive verifies the session before adding it. +The registry opens the `workspace` domain (version 2): a `workspaces` table keyed by `WorkspaceId` plus one global state holding `workspaceIds` (the authoritative display order), `archivedSessionIds`, `pinnedSessionIds`, the optional `defaultWorkspaceId` first-use identity, and the optional `pendingMutation` marker. Archive and pin sets contain Session id strings, default to empty, and carry no per-entry objects or timestamps; the pin array keeps the most recently pinned id first. Archiving clears the pin in the same global-state write without changing Workspace membership. Unarchive runs no session-existence probe, because dropping an id from the set cannot introduce an unknown one, while archive verifies the session before adding it. ### Lifecycle diff --git a/packages/workspace/workspace/README.zh.md b/packages/workspace/workspace/README.zh.md index 102308d325..3d458e1315 100644 --- a/packages/workspace/workspace/README.zh.md +++ b/packages/workspace/workspace/README.zh.md @@ -33,7 +33,7 @@ kind: "package-reference" ### 设置 -此包本身不声明任何配置;它需要会话存储、会话持久化后端,以及保存其记录的存储行。最小组合如下: +此包需要会话存储、会话持久化后端,以及保存其记录的存储行。最小组合如下: ```yaml - name: '@deepseek-ai/dsh-session' @@ -59,6 +59,15 @@ await project.setTitle('Renamed') ctx.workspaceRegistry.list() // shows the project, newest first ``` + +### 首次使用工作区 + +`initializeDefault(resolveDirectory)` 初始化默认 Workspace,不创建 Session。首次创建要求 Workspace 注册表为空,且不存在运行时、持久化或已归档 Session,包括没有工作目录的 Session。注册表直接检查持久化历史;仅凭可见侧边栏为空不足以判断。 + +目录解析器仅在允许创建时于变更队列内运行。它返回绝对路径和初始标题;注册表创建缺失的父目录、规范化路径、重新检查 Session 历史,再一起提交 Workspace 和初始化标记。已存在的目录直接复用;文件冲突或目录操作失败时拒绝初始化。[Host 控制器](../../api/workspace-controller/README.zh.md#first-use-workspace)提供 Documents 路径策略。 + +首次成功登记会持久保存工作区身份。重复调用直接返回它,不再解析目录;改名保留该身份,删除登记也不会允许再次自动创建。目录或登记失败时,初始化状态保持未设置,可以重试。后续步骤失败前已创建的目录会保留在磁盘上。[首次使用决策](../../../.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md)说明这一生命周期。 + ### 将会话归入项目 会话加入它运行目录所在的项目:在项目目录中创建会话,它就会出现在该项目下,新到旧排列。一个会话只能属于一个项目。目录无法校验的会话——没有记录目录,或目录被移动、删除——无法加入,保持 Ungrouped。 @@ -102,7 +111,7 @@ ctx.workspaceRegistry.list() // shows the project, newest first ### 持久形态 -注册表打开 `workspace` 领域(版本 2):一张以 `WorkspaceId` 为键的 `workspaces` 表,加上一个持有 `workspaceIds`(权威显示顺序)、`archivedSessionIds`、`pinnedSessionIds` 与可选 `pendingMutation` 标记的全局状态。归档与置顶集合存储会话 id 字符串,默认值为空,不包含逐项对象或时间戳;置顶数组把最近置顶的 id 放在前面。归档在同一次全局状态写入中清除置顶,但不改变 Workspace 成员关系。取消归档不做会话存在性探测,因为从集合中移除 id 不可能引入未知 id,而归档会在加入前校验会话。 +注册表打开 `workspace` 领域(版本 2):一张以 `WorkspaceId` 为键的 `workspaces` 表,加上一个持有 `workspaceIds`(权威显示顺序)、`archivedSessionIds`、`pinnedSessionIds`、可选的首次使用身份 `defaultWorkspaceId` 与可选 `pendingMutation` 标记的全局状态。归档与置顶集合存储会话 id 字符串,默认值为空,不包含逐项对象或时间戳;置顶数组把最近置顶的 id 放在前面。归档在同一次全局状态写入中清除置顶,但不改变 Workspace 成员关系。取消归档不做会话存在性探测,因为从集合中移除 id 不可能引入未知 id,而归档会在加入前校验会话。 ### 生命周期 diff --git a/packages/workspace/workspace/src/index.ts b/packages/workspace/workspace/src/index.ts index ab9ff50409..6cb179022a 100644 --- a/packages/workspace/workspace/src/index.ts +++ b/packages/workspace/workspace/src/index.ts @@ -6,7 +6,7 @@ */ import { randomUUID } from 'node:crypto' -import { stat } from 'node:fs/promises' +import { mkdir, stat } from 'node:fs/promises' import { Context, Service } from '@deepseek-ai/cordis' import type { SessionHeader, SessionId } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-session-persistence' @@ -15,7 +15,7 @@ import { WorkspaceEntity } from './entity.ts' import type { WorkspaceEntityHost } from './entity.ts' export { WorkspaceMoveInvalidError } from './entity.ts' -import { defaultWorkspaceTitle, realpathNormalize } from './paths.ts' +import { defaultWorkspaceTitle, fullyQualifiedWorkspacePath, realpathNormalize } from './paths.ts' import { workspaceDomainSpec } from './spec.ts' import type { WorkspaceDomainState, WorkspaceRecord } from './spec.ts' import type { Workspace, WorkspaceId as WorkspaceIdBrand } from './types.ts' @@ -175,6 +175,34 @@ export class WorkspaceRegistry extends Service { return await this.enqueueOperation(() => this.createCanonical(canonical, title)) } + /** + * Initialize the default Workspace only while both the registry and Session + * history are empty. Repeated requests reuse its durable identity; deleting + * that registration permanently disables automatic creation. + * @param resolveDirectory - resolve the absolute directory and initial title; + * called only for eligible creation, inside the registry mutation queue. + * Missing directories are created recursively before registration. + * @returns the initialized Workspace, or undefined when automatic creation is ineligible. + */ + initializeDefault(resolveDirectory: () => Promise<{ path: string; title: string }>): Promise { + return this.enqueueOperation(async () => { + const state = this.requireState() + if (state.defaultWorkspaceId !== undefined) return this.entities.get(state.defaultWorkspaceId) + const sessions = this.ctx.get('sessions') + if (sessions === undefined) throw new Error('default Workspace initialization requires the Session store') + if (state.workspaceIds.length > 0 || state.archivedSessionIds.length > 0 + || sessions.list().length > 0 || (await this.listStoredHeaders()).length > 0) return undefined + + const { path, title } = await resolveDirectory() + if (!fullyQualifiedWorkspacePath(path)) throw new TypeError(`Workspace path is not fully qualified: '${path}'`) + await mkdir(path, { recursive: true }) + const canonical = await realpathNormalize(path) + // A Session can start outside the registry queue while directory preparation awaits I/O. + if ((await this.listStoredHeaders()).length > 0 || sessions.list().length > 0) return undefined + return this.createCanonical(canonical, title, true) + }) + } + /** * Look up a workspace by id. * @param id - Workspace id. @@ -379,7 +407,7 @@ export class WorkspaceRegistry extends Service { return undefined } - private async createCanonical(canonical: string, title?: string): Promise { + private async createCanonical(canonical: string, title?: string, firstUse = false): Promise { for (const entity of this.entities.values()) { if (entity.path === canonical) return entity } @@ -425,7 +453,10 @@ export class WorkspaceRegistry extends Service { try { await this.setState({ + ...state, + pendingMutation: undefined, initialized: true, + ...(firstUse ? { defaultWorkspaceId: id } : {}), workspaceIds: [id, ...state.workspaceIds], archivedSessionIds: state.archivedSessionIds, pinnedSessionIds: state.pinnedSessionIds, @@ -458,6 +489,8 @@ export class WorkspaceRegistry extends Service { if (entity === undefined) return false const state = this.requireState() const nextState = { + ...state, + pendingMutation: undefined, initialized: true, workspaceIds: state.workspaceIds.filter(workspaceId => workspaceId !== id), archivedSessionIds: state.archivedSessionIds, @@ -516,6 +549,8 @@ export class WorkspaceRegistry extends Service { } await this.requireTable().delete(pending.workspaceId) await this.setState({ + ...state, + pendingMutation: undefined, initialized: state.initialized, workspaceIds: state.workspaceIds, archivedSessionIds: state.archivedSessionIds, diff --git a/packages/workspace/workspace/src/spec.ts b/packages/workspace/workspace/src/spec.ts index 165bff34e0..9bd792258a 100644 --- a/packages/workspace/workspace/src/spec.ts +++ b/packages/workspace/workspace/src/spec.ts @@ -56,6 +56,8 @@ const workspacePendingMutation = z.discriminatedUnion('operation', [ */ export const workspaceDomainState = z.object({ initialized: z.boolean(), + /** First-use Workspace identity, retained after its registration is deleted. */ + defaultWorkspaceId: workspaceId.optional(), workspaceIds: z.array(workspaceId), archivedSessionIds: z.array(sessionId).default([]), pinnedSessionIds: z.array(sessionId).default([]), diff --git a/packages/workspace/workspace/tests/workspace.spec.ts b/packages/workspace/workspace/tests/workspace.spec.ts index f860028d4e..6eafae9f2e 100644 --- a/packages/workspace/workspace/tests/workspace.spec.ts +++ b/packages/workspace/workspace/tests/workspace.spec.ts @@ -2,7 +2,7 @@ import type { z } from 'zod' import { afterEach, describe, expect, it, vi } from 'vitest' import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' -import { basename, join } from 'node:path' +import { basename, join, relative } from 'node:path' import { Context } from '@deepseek-ai/cordis' import Storage from '@deepseek-ai/dsh-storage' import type { StorageBackend } from '@deepseek-ai/dsh-storage' @@ -1156,3 +1156,145 @@ describe('registry-global session unpin', () => { expect(result.list.mock.calls.length).toBe(listingsBefore) }) }) + +describe('first-use Workspace preparation', () => { + const contexts: Context[] = [] + + afterEach(async () => { + for (const ctx of contexts.splice(0)) await ctx.fiber.dispose() + }) + + async function firstUse(options: HarnessOptions = {}) { + const directoryRoot = await makeDir('first-use') + const result = await harness({ liveSessions: [], ...options }) + contexts.push(result.ctx) + const resolveDirectory = vi.fn(async () => ({ path: join(directoryRoot, 'nested', 'Workspace'), title: 'Workspace' })) + return { ...result, directoryRoot, resolveDirectory } + } + + it('creates parent directories and resolves only one directory for concurrent initialization', async () => { + const h = await firstUse() + const laterDirectory = vi.fn(async () => { throw new Error('directory lookup unavailable') }) + const [first, repeated] = await Promise.all([ + h.registry.initializeDefault(h.resolveDirectory), h.registry.initializeDefault(laterDirectory), + ]) + expect(first).toBeDefined() + expect(repeated).toBe(first) + expect(h.resolveDirectory).toHaveBeenCalledOnce() + expect(laterDirectory).not.toHaveBeenCalled() + expect(first?.path).toBe(await realpath(join(h.directoryRoot, 'nested', 'Workspace'))) + expect(first?.title).toBe('Workspace') + expect(h.registry.list()).toEqual([first]) + expect(storedState(h.pool).defaultWorkspaceId).toBe(first?.id) + expect(h.ctx.sessions.list()).toEqual([]) + expect(h.open).not.toHaveBeenCalled() + }) + + it('reuses an existing directory without changing its contents', async () => { + const h = await firstUse() + const directory = join(h.directoryRoot, 'nested', 'Workspace') + await mkdir(directory, { recursive: true }) + await writeFile(join(directory, 'keep.txt'), 'keep') + expect((await h.registry.initializeDefault(h.resolveDirectory))?.path).toBe(directory) + const { readFile } = await import('node:fs/promises') + expect(await readFile(join(directory, 'keep.txt'), 'utf8')).toBe('keep') + }) + + it('leaves initialization retryable when directory resolution fails', async () => { + const h = await firstUse() + h.resolveDirectory.mockRejectedValueOnce(new Error('lookup unavailable')) + await expect(h.registry.initializeDefault(h.resolveDirectory)).rejects.toThrow('lookup unavailable') + expect(storedState(h.pool).defaultWorkspaceId).toBeUndefined() + expect(await h.registry.initializeDefault(h.resolveDirectory)).toBeDefined() + }) + + it('rejects a relative candidate before creating its directory', async () => { + const h = await firstUse() + const candidate = join(h.directoryRoot, 'relative') + h.resolveDirectory.mockResolvedValueOnce({ path: relative(process.cwd(), candidate), title: 'Workspace' }) + await expect(h.registry.initializeDefault(h.resolveDirectory)).rejects.toThrow('fully qualified') + await expect(realpath(candidate)).rejects.toMatchObject({ code: 'ENOENT' }) + expect(h.registry.list()).toEqual([]) + expect(storedState(h.pool).defaultWorkspaceId).toBeUndefined() + }) + + it('keeps the initialization marker across deletion and restart', async () => { + const h = await firstUse() + const workspace = (await h.registry.initializeDefault(h.resolveDirectory))! + await workspace.setTitle('Renamed') + expect((await h.registry.initializeDefault(h.resolveDirectory))?.title).toBe('Renamed') + await h.registry.delete(workspace.id) + await h.ctx.fiber.dispose() + const restarted = await firstUse({ pool: h.pool }) + await expect(restarted.registry.initializeDefault(restarted.resolveDirectory)).resolves.toBeUndefined() + expect(storedState(h.pool).defaultWorkspaceId).toBe(workspace.id) + expect(restarted.registry.list()).toEqual([]) + expect(restarted.resolveDirectory).not.toHaveBeenCalled() + }) + + it.each(['persisted', 'live', 'archived'] as const)('refuses automatic creation for a %s cwd-less Session', async (kind) => { + const history = header('old') + const h = await firstUse(kind === 'persisted' ? { sessions: [history] } : { liveSessions: [history] }) + if (kind === 'archived') await h.registry.archiveSession(history.id) + await expect(h.registry.initializeDefault(h.resolveDirectory)).resolves.toBeUndefined() + expect(h.registry.list()).toEqual([]) + expect(storedState(h.pool).defaultWorkspaceId).toBeUndefined() + expect(h.resolveDirectory).not.toHaveBeenCalled() + }) + + it('refuses a non-empty Workspace list and newly persisted history', async () => { + const h = await firstUse() + const explicit = await h.registry.create(h.directoryRoot) + await expect(h.registry.initializeDefault(h.resolveDirectory)).resolves.toBeUndefined() + await h.registry.delete(explicit.id) + h.setSessions([header('arrived')]) + await expect(h.registry.initializeDefault(h.resolveDirectory)).resolves.toBeUndefined() + }) + + it('fails on a same-path file and remains eligible after it is removed', async () => { + const h = await firstUse() + const parent = join(h.directoryRoot, 'nested') + await mkdir(parent) + const path = join(parent, 'Workspace') + await writeFile(path, 'occupied') + await expect(h.registry.initializeDefault(h.resolveDirectory)).rejects.toThrow() + expect(storedState(h.pool).defaultWorkspaceId).toBeUndefined() + expect(h.registry.list()).toEqual([]) + await rm(path) + expect((await h.registry.initializeDefault(h.resolveDirectory))?.path).toBe(path) + }) + + it.each(['persisted', 'live'] as const)('refuses registration when a %s Session appears during directory preparation', async (kind) => { + const h = await firstUse() + const arrived = header('arrived-during-preparation') + if (kind === 'persisted') { + h.list.mockResolvedValueOnce([]).mockResolvedValueOnce([ + { header: arrived, revision: SessionPersistenceRevision('arrived-revision') }, + ]) + } else { + vi.spyOn(h.ctx.sessions, 'list').mockReturnValueOnce([]).mockReturnValueOnce([{ header: arrived }] as never) + } + await expect(h.registry.initializeDefault(h.resolveDirectory)).resolves.toBeUndefined() + expect(h.registry.list()).toEqual([]) + expect(storedState(h.pool).defaultWorkspaceId).toBeUndefined() + }) + + it('does not infer an empty live Session store when the peer is unavailable', async () => { + const h = await harness() + contexts.push(h.ctx) + const resolveDirectory = vi.fn(async () => { throw new Error('unexpected directory lookup') }) + await expect(h.registry.initializeDefault(resolveDirectory)).rejects.toThrow('Session store') + expect(resolveDirectory).not.toHaveBeenCalled() + expect(storedState(h.pool).defaultWorkspaceId).toBeUndefined() + }) + + it('rolls back a failed final marker write and allows a retry', async () => { + const pool = new MemoryMediaPool() + const h = await firstUse({ pool, backend: selectiveFailureBackend(pool, { globalAt: 3 }) }) + await expect(h.registry.initializeDefault(h.resolveDirectory)).rejects.toThrow('marker failure') + expect(h.registry.list()).toEqual([]) + expect(storedState(pool).defaultWorkspaceId).toBeUndefined() + await expect(realpath(join(h.directoryRoot, 'nested', 'Workspace'))).resolves.toBe(join(h.directoryRoot, 'nested', 'Workspace')) + expect(await h.registry.initializeDefault(h.resolveDirectory)).toBeDefined() + }) +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index dc16be7fbf..6543dd2ade 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1297,6 +1297,12 @@ importers: '@deepseek-ai/dsh-deque': specifier: workspace:^ version: link:../../util/deque + '@deepseek-ai/dsh-native-command': + specifier: workspace:^ + version: link:../../util/native-command + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery zod: specifier: ^4.4.3 version: 4.4.3 diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index c3a8c6a239..1f19959e7e 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -246,6 +246,7 @@ export const EVENT_SCOPE_PAGE: Record = { export const EVENT_WALK_EXEMPTIONS: Record = { 'command/executed': 'client-face local command acknowledgment — packages/client/ui-commands/README.md owns the API', 'connection/reset': 'client-face transport signal — packages/api/session-controller/README.md owns the API', + 'conversation/prepare-first-send': 'client-face first-use draft preparation — packages/client/ui-conversation/README.md owns the API', 'locale/change': 'client-face locale switch signal — packages/client/locale/README.md owns the API', 'slash/input-begin-command': 'client-face slash-input protocol — packages/client/ui-input-trigger/README.md owns the API', 'slash/input-consume-token': 'client-face slash-input protocol — packages/client/ui-input-trigger/README.md owns the API', @@ -681,6 +682,7 @@ export const LINK_MAP: Readonly> = { WorkspaceArchiveSessionRequest: 'workspace.md', WorkspaceArchiveValue: 'workspace.md', WorkspaceCreateRequest: 'workspace.md', + WorkspaceInitializeDefaultRequest: 'workspace.md', WorkspaceCreateValue: 'workspace.md', WorkspaceDeleteRequest: 'workspace.md', WorkspaceDeleteValue: 'workspace.md', diff --git a/snapshots/web/default-workspace/snapshot.yml b/snapshots/web/default-workspace/snapshot.yml new file mode 100644 index 0000000000..d1eed14d70 --- /dev/null +++ b/snapshots/web/default-workspace/snapshot.yml @@ -0,0 +1,9 @@ +version: 1 +scenario: default-workspace +profile: web +composition: web-default +recording: authored +header: + class: web-default +session: + source: ../fresh-round-trip/session.v3.jsonl diff --git a/snapshots/web/default-workspace/ui.expected.md b/snapshots/web/default-workspace/ui.expected.md new file mode 100644 index 0000000000..425343834b --- /dev/null +++ b/snapshots/web/default-workspace/ui.expected.md @@ -0,0 +1,26 @@ +- banner: + - navigation "Session hierarchy": Use the bash tool to + - text: Standard mode + - button "More actions" + - button "Open right sidebar" + - tablist: + - tab "Chat" [selected] + - tab "Trajectory" +- button "System prompt" +- text: "Use the bash tool to run exactly: echo WEB_E2E_OK. Then reply with the single word DONE and stop. {{clock}}" +- button "Copy" +- button "1 tool call" +- paragraph: DONE +- button "Copy" +- button "Good response" +- button "Bad response" +- button "Branch into a new conversation" +- text: {{clock}} +- textbox "Message or run a task, / commands, @ files or sessions" +- button "Add files or run commands" +- 'button "Access mode, current: Workspace Write"': Workspace Write +- button "Select model, current DeepSeek-V4-Flash": DeepSeek-V4-Flash +- button "Send message" [disabled] +- button "1 turns 2 steps · {{throughput}} tok/s": 1 turns 2 steps{{throughput}} tok/s +- button "15.8K tok · Cache hit 99%": 15.8K tokCache hit 99% +- button "6% of context used": 6% diff --git a/tsconfig.host.json b/tsconfig.host.json index c1088e0ae8..0e9797b99b 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -63,6 +63,7 @@ "apps/web/tests/public-mount.e2e.ts", "apps/web/tests/workspace-new-session-folding.e2e.ts", "apps/web/tests/workspace-management.e2e.ts", + "apps/web/tests/default-workspace.e2e.ts", "apps/web/tests/workspace-recency.e2e.ts", "apps/web/tests/session-unarchive.e2e.ts", "apps/web/tests/replay-round-trip.e2e.ts", From 6fa56a0cf7c0d7d588a4f94549e82a4936e2cfa6 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 15:57:45 +0800 Subject: [PATCH 04/27] fix(conversation): preserve first drafts across Session retirement --- .../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 | 2 + .../src/client/input/first-draft.ts | 5 +- .../tests/apply-inject.client.spec.tsx | 61 ++++++++++++++++++- .../tests/first-draft.client.spec.ts | 2 +- 7 files changed, 71 insertions(+), 7 deletions(-) diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 2002de04c1..d9ee350eac 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md -README.md: 56b9d06ce5e48ab40691bede2ccb9669e180aa9f -README.zh.md: fd02565698171e0b6db35080181e57b8b5abd42d +README.md: 6ea403d46b9a019cbd24f8963a89835be4745980 +README.zh.md: f6e28d563847316b538ab8c4317507ea7761c913 diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 56b9d06ce5..6ea403d46b 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -52,7 +52,7 @@ Workspace selection uses `uiWorkspace.openWorkspace` to prepare the target and c The Client chooses the default directory name and initial title when sending: Chinese uses `默认工作区`, English uses `Default workspace`, and other languages use directory `default-workspace` with title `Default workspace`. The request retains those names during initialization. A retry after failed initialization uses the current language; a successfully initialized Workspace keeps its directory and title across language changes. -On first use, the same input accepts text before a Workspace is selected. The first send prepares the [default Workspace](../../workspace/workspace/README.md#first-use-workspace), selects its blank Session, transfers the draft, and uses ordinary message submission. Preparation locks further input. Failure preserves the draft and offers Cancel or Choose folder through the existing picker. A manually chosen folder receives the unsent draft; the user sends again. Once created, the Workspace survives a prompt failure. `conversation/prepare-first-send` awaits staged Session settings before automatically submitting the transferred first-use draft; a rejected listener keeps that draft and reports its error. +On first use, the same input accepts text before a Workspace is selected. The first send prepares the [default Workspace](../../workspace/workspace/README.md#first-use-workspace), selects its blank Session, transfers the draft, and uses ordinary message submission. Preparation locks further input. Failure preserves the draft and offers Cancel or Choose folder through the existing picker. A manually chosen folder receives the unsent draft; the user sends again. Once created, the Workspace survives a prompt failure. `conversation/prepare-first-send` awaits staged Session settings before automatically submitting the transferred first-use draft; a rejected listener keeps that draft and reports its error. If navigation releases the destination Session while preparation is pending, automatic submission stops and its persisted draft remains available on reopening. The package occupies the root-scoped `main` key `conversation`. Its `main.conversation` shell keeps the resident `conversation.header` outside the optional-Session `conversation.content` Component Factory. The header hosts root-scoped navigation without a selected Session; titles, actions, and View tabs remain in its strict Session child. The Factory owns the shared body and Composer, reads the current Session through its standard Hook, and exposes strict-Session `views` plus root-scoped `widthControls` local positions. Its default adapter renders the existing `conversation.session` entry, while the main occurrence selects the width handles; an embedded occurrence can replace `views` and omit those handles without rendering the main Header. The shared body and Composer register the queue and Todo docks. The Todo dock uses the shared panel elevation above the composer; its rows use the shared idle, ongoing, and done markers for pending, in-progress, and completed items. `ctx.uiSession.provide()` materializes the Conversation and input sources from the same Session binding and supplies `inputActions` as a stable standard prop. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index fd02565698..f6e28d5638 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -52,7 +52,7 @@ target package 通过 declaration merge 扩展 snapshot 与 Location data map, Client 在发送时决定默认目录名和初始标题:中文使用 `默认工作区`,英文使用 `Default workspace`,其他语言使用目录 `default-workspace` 和标题 `Default workspace`。初始化期间,请求保留这些名称。初始化失败后的重试使用当前语言;初始化成功的 Workspace 在切换语言后仍保留原目录和标题。 -首次使用时,同一个输入框允许在选择 Workspace 前输入文字。首条消息会准备[默认工作区](../../workspace/workspace/README.zh.md#first-use-workspace)、选中其 blank Session、转移草稿,再使用普通消息提交流程。准备期间锁定后续输入。失败时保留草稿,并提供“取消”或通过已有选择器“选择文件夹”。手动选择的文件夹接收未发送草稿,用户再次发送。Workspace 创建成功后,不会因提示词发送失败而消失。`conversation/prepare-first-send` 在自动提交已转移的首次使用草稿前等待暂存的 Session 设置完成;监听器拒绝时保留该草稿并显示错误。 +首次使用时,同一个输入框允许在选择 Workspace 前输入文字。首条消息会准备[默认工作区](../../workspace/workspace/README.zh.md#first-use-workspace)、选中其 blank Session、转移草稿,再使用普通消息提交流程。准备期间锁定后续输入。失败时保留草稿,并提供“取消”或通过已有选择器“选择文件夹”。手动选择的文件夹接收未发送草稿,用户再次发送。Workspace 创建成功后,不会因提示词发送失败而消失。`conversation/prepare-first-send` 在自动提交已转移的首次使用草稿前等待暂存的 Session 设置完成;监听器拒绝时保留该草稿并显示错误。如果导航在准备期间释放了目标 Session,自动提交会停止,已持久化的草稿会在重新打开时保留。 本包占据 root 作用域 `main` 中的 `conversation` key。其 `main.conversation` 外壳将常驻的 `conversation.header` 放在可选 Session 的 `conversation.content` Component Factory 外。未选中 Session 时,头部仍承载根作用域导航;标题、操作和 View 标签保留在严格 Session 子组件中。Factory 拥有共享正文与 Composer,通过其标准 Hook 读取当前 Session,并公开 strict-Session `views` 与 root-scoped `widthControls` 两个局部位置。默认 adapter 渲染现有 `conversation.session` entry,主 occurrence 选择宽度拖拽条;嵌入式 occurrence 可以替换 `views`、省略拖拽条,且不渲染主 Header。共享正文与 Composer 注册 queue dock 和 Todo dock。Todo dock 在 composer 上方使用共享面板 elevation;其中的行分别以共享 idle、ongoing 与 done 标记表示待处理、进行中与已完成。`ctx.uiSession.provide()` 从同一个 Session binding 物化 Conversation 与 input source,并将 `inputActions` 作为稳定标准 prop 提供。 diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index 02c1f3a593..018cf29579 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -208,6 +208,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { const firstDraft = new FirstDraft(ctx, { open: (beforeOpen, signal) => { const language = ctx.locale.getSnapshot().active.toLowerCase().split('-')[0] + // Persisted Workspace names follow the send-time language, including the English fallback. const title = (language === 'zh' ? zh : en)['defaultWorkspace.title'] return workspaceNavigation.openDefaultWorkspace({ directoryName: language === 'zh' || language === 'en' ? title : 'default-workspace', @@ -215,6 +216,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { }, beforeOpen, signal) }, shell: id => inputHub.shell(id), + isCurrent: (id, shell) => sessions.binding(id) !== undefined && inputHub.shell(id) === shell, }) const composerBlocks = new ComposerBlockRegistry() diff --git a/packages/client/ui-conversation/src/client/input/first-draft.ts b/packages/client/ui-conversation/src/client/input/first-draft.ts index 9e1c486eae..8dc7fb32a6 100644 --- a/packages/client/ui-conversation/src/client/input/first-draft.ts +++ b/packages/client/ui-conversation/src/client/input/first-draft.ts @@ -10,13 +10,15 @@ import { SessionInputShell } from './facade.ts' interface FirstDraftDeps { open(beforeOpen: (id: SessionId) => void, signal: AbortSignal): Promise shell(id: SessionId): SessionInputShell + /** Whether the borrowed input still belongs to the retained Session generation. */ + isCurrent(id: SessionId, shell: SessionInputShell): boolean } /** Owns a root-lifetime text editor without allocating a Host Session. */ export class FirstDraft { /** Preparation progress and the recoverable directory failure. */ readonly state = createSnapshotStore({ busy: false, failed: false }) - /** Local editor that stays independent of Host Session allocation. */ + /** Local editor owns failed-submit restoration before transfer to a Host Session. */ readonly shell: SessionInputShell private pending: { text: string; transferred: boolean } | undefined @@ -63,6 +65,7 @@ export class FirstDraft { target = this.deps.shell(id) await this.ctx.serial('conversation/prepare-first-send', id) signal.throwIfAborted() + if (!this.deps.isCurrent(id, target)) return { kind: 'success' } target.submit(mode) return { kind: 'success' } } catch (error) { diff --git a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx index abc74918d5..c35aff8227 100644 --- a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx @@ -139,11 +139,70 @@ async function bench() { return { runtime, feature, slots: runtime.slots, entryOf, conversationApi, headerApi, residentApi, composerApi, inputApi, viewSource, sessionFake, connectWorkspace, rootUpload, uploads, rootReference, references, opened, - locale, openDefaultWorkspace, + locale, openDefaultWorkspace, replaceMain, } } describe('Conversation inject API', () => { + it.each([false, true])('keeps the saved first draft after its Session retires (reopened during preparation: %s)', async (reopenEarly) => { + const b = await bench() + onTestFinished(() => b.runtime.dispose()) + const settings = Promise.withResolvers() + const started = Promise.withResolvers() + b.runtime.ctx.on('conversation/prepare-first-send', () => { + started.resolve(undefined) + return settings.promise + }) + b.openDefaultWorkspace.mockImplementation(async (_request, beforeOpen) => { + b.replaceMain(ROOT, beforeOpen) + return ROOT + }) + const body = b.conversationApi(ROOT) + const unmirror = body.injected.bindDraftMirror(body.instance.actions.setDraft) + const composer = b.composerApi(undefined) + let reopened: SessionReference | undefined + try { + composer.keyboard.paste('keep this first draft') + composer.keyboard.submit('queue') + await started.promise + expect(body.instance.store.getSnapshot().draft).toBe('keep this first draft') + const other = 'other-first-send' as SessionId + await b.runtime.sessions.add({ id: other, session: sessionFakeFor() }) + unmirror() + b.rootReference.release() + b.replaceMain(other) + await vi.waitFor(() => { expect(b.runtime.sessions.binding(ROOT)).toBeUndefined() }) + if (reopenEarly) reopened = b.runtime.sessions.retain(ROOT) + settings.resolve(undefined) + await vi.waitFor(() => { expect(b.residentApi(undefined).hooks.firstDraft.getSnapshot().busy).toBe(false) }) + await b.runtime.flush() + expect(b.sessionFake.prompt).not.toHaveBeenCalled() + reopened ??= b.runtime.sessions.retain(ROOT) + b.references.set(ROOT, reopened) + expect(b.conversationApi(ROOT).instance.store.getSnapshot().draft).toBe('keep this first draft') + expect(composer.hooks.composerInput.getSnapshot().draft).toBe('') + } finally { + settings.resolve(undefined) + reopened?.release() + unmirror() + } + }) + + it('submits the first draft through its retained destination input', async () => { + const b = await bench() + onTestFinished(() => b.runtime.dispose()) + b.openDefaultWorkspace.mockImplementation(async (_request, beforeOpen) => { + b.replaceMain(ROOT, beforeOpen) + return ROOT + }) + const composer = b.composerApi(undefined) + composer.keyboard.paste('first message') + composer.keyboard.submit('queue') + await vi.waitFor(() => { expect(b.sessionFake.prompt).toHaveBeenCalledOnce() }) + expect(b.sessionFake.prompt.mock.calls[0]?.[0]).toEqual([{ type: 'text', text: 'first message' }]) + expect(composer.hooks.composerInput.getSnapshot().draft).toBe('') + }) + it.each([ ['zh', '默认工作区', '默认工作区'], ['en', 'Default workspace', 'Default workspace'], diff --git a/packages/client/ui-conversation/tests/first-draft.client.spec.ts b/packages/client/ui-conversation/tests/first-draft.client.spec.ts index 3d223a38fe..b23055dcf1 100644 --- a/packages/client/ui-conversation/tests/first-draft.client.spec.ts +++ b/packages/client/ui-conversation/tests/first-draft.client.spec.ts @@ -27,7 +27,7 @@ function harness() { beforeOpen = prepare return opened.promise }) - const first = new FirstDraft(ctx, { open, shell: () => target }) + const first = new FirstDraft(ctx, { open, shell: () => target, isCurrent: () => true }) return { ctx, first, target, submitted, open, opened, complete: () => { From cfec29eb69bf8c4c78b388547502e324e0e1ecd4 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 15:58:10 +0800 Subject: [PATCH 05/27] fix(web): show first-use preparation and update browser readiness --- apps/web/tests/default-workspace.e2e.ts | 20 ++++++++++++++++--- .../default-workspace/preparing.expected.md | 7 +++++++ apps/web/tests/preview-boot.e2e.ts | 4 ++-- apps/web/tests/sessionless-header.e2e.ts | 2 +- apps/web/tests/startup-rpc-budget.e2e.ts | 2 +- apps/web/tests/support.ts | 4 ++-- .../ui-conversation/src/client/locales.ts | 2 ++ .../client/skeleton/ConversationContent.tsx | 2 +- .../tests/skeleton.client.spec.tsx | 1 + snapshots/web/default-workspace/snapshot.yml | 2 ++ .../workspace.expected/.empty | 1 + 11 files changed, 37 insertions(+), 10 deletions(-) create mode 100644 apps/web/tests/expected/default-workspace/preparing.expected.md create mode 100644 snapshots/web/default-workspace/workspace.expected/.empty diff --git a/apps/web/tests/default-workspace.e2e.ts b/apps/web/tests/default-workspace.e2e.ts index 00bec9de3c..265fa715b2 100644 --- a/apps/web/tests/default-workspace.e2e.ts +++ b/apps/web/tests/default-workspace.e2e.ts @@ -3,9 +3,9 @@ import { mkdir, readFile, stat, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { chromium } from 'playwright' -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { - captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, launchWebScaffold, + assertFinalWorkspaceSnapshot, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, launchWebScaffold, selectedSessionFixture, watchConsole, webSnapshotMode, } from './scaffold.ts' import { newEnglishPage, saveFailureShot } from './support.ts' @@ -13,6 +13,7 @@ import { newEnglishPage, saveFailureShot } from './support.ts' const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/fresh-round-trip/session.v3.jsonl', import.meta.url)) const EXPECTED = fileURLToPath(new URL('../../../snapshots/web/default-workspace/ui.expected.md', import.meta.url)) const FAILURE_EXPECTED = fileURLToPath(new URL('./expected/default-workspace/failure.expected.md', import.meta.url)) +const PREPARING_EXPECTED = fileURLToPath(new URL('./expected/default-workspace/preparing.expected.md', import.meta.url)) const MODE = webSnapshotMode() describe.skipIf(MODE === 'record')('web e2e: default Workspace', () => { @@ -38,7 +39,19 @@ describe.skipIf(MODE === 'record')('web e2e: default Workspace', () => { expect(scaffold.ctx.workspaceRegistry.list()).toEqual([]) expect(scaffold.ctx.sessions.list()).toEqual([]) const settled = scaffold.whenTurnSettled() - await input.press('Enter') + const preparing = Promise.withResolvers() + const initialize = scaffold.ctx.workspaceRegistry.initializeDefault.bind(scaffold.ctx.workspaceRegistry) + vi.spyOn(scaffold.ctx.workspaceRegistry, 'initializeDefault').mockImplementationOnce(async (resolve) => { + await preparing.promise + return initialize(resolve) + }) + try { + await input.press('Enter') + await page.getByRole('textbox', { name: 'Preparing workspace…', exact: true }).waitFor() + await compareOrRefreshGolden(PREPARING_EXPECTED, await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd), MODE) + } finally { + preparing.resolve(undefined) + } const sessionId = await settled const workspace = scaffold.ctx.workspaceRegistry.list()[0]! expect(workspace.title).toBe('Default workspace') @@ -46,6 +59,7 @@ describe.skipIf(MODE === 'record')('web e2e: default Workspace', () => { expect((await stat(workspace.path)).isDirectory()).toBe(true) expect(workspace.sessionIds).toContain(sessionId) expect(scaffold.ctx.sessions.get(sessionId)?.header.cwd).toBe(workspace.path) + await assertFinalWorkspaceSnapshot(fileURLToPath(new URL('../../../snapshots/web/default-workspace', import.meta.url)), workspace.path) await page.getByText('DONE', { exact: true }).waitFor() await compareOrRefreshGolden(EXPECTED, await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd), MODE) await page.reload() diff --git a/apps/web/tests/expected/default-workspace/preparing.expected.md b/apps/web/tests/expected/default-workspace/preparing.expected.md new file mode 100644 index 0000000000..09e86fbb6e --- /dev/null +++ b/apps/web/tests/expected/default-workspace/preparing.expected.md @@ -0,0 +1,7 @@ +- banner +- text: Into the Unknown Preview +- button "Choose workspace" +- button "Standard mode" +- textbox "Preparing workspace…" [disabled] +- button "Add files or run commands" [disabled] +- button "Send message" [disabled] diff --git a/apps/web/tests/preview-boot.e2e.ts b/apps/web/tests/preview-boot.e2e.ts index bde54fe69e..4797a6e4bf 100644 --- a/apps/web/tests/preview-boot.e2e.ts +++ b/apps/web/tests/preview-boot.e2e.ts @@ -297,7 +297,7 @@ async function bootPreview(origin: string, browser: Browser): Promise { expect(await page.getByText('Empty environment', { exact: true }).count()).toBe(1) expect(await page.getByText('WebFS directory', { exact: true }).count()).toBe(1) expect(await page.locator('input[name="preview-source"][value="webfs"]').isDisabled()).toBe(true) - expect(await page.getByRole('textbox', { name: 'Choose workspace' }).count()).toBe(0) + expect(await page.getByRole('button', { name: 'Choose workspace' }).count()).toBe(0) await compareOrRefreshGolden( SOURCE_CHOOSER_EXPECTED, await captureStableAria(page, '[data-preview-source-card]', '/__preview_no_workspace__'), @@ -471,7 +471,7 @@ async function bootEmptyPreview(origin: string, browser: Browser): Promise ) expect(bootLine).toContain(`image lowering=${WRAPPER_CONTRACT}`) expect(bootLine).toContain('data overlays=0') - await page.getByRole('textbox', { name: 'Choose workspace' }).waitFor({ timeout: HERO_TIMEOUT_MS }) + await page.getByRole('button', { name: 'Choose workspace' }).waitFor({ timeout: HERO_TIMEOUT_MS }) const sessionCount = await page.evaluate(async () => { const transport = (globalThis as typeof globalThis & { __DSH_TRANSPORT__?: { fetch(input: string, init: RequestInit): Promise } diff --git a/apps/web/tests/sessionless-header.e2e.ts b/apps/web/tests/sessionless-header.e2e.ts index b2c1a85fb0..1de5dfe14f 100644 --- a/apps/web/tests/sessionless-header.e2e.ts +++ b/apps/web/tests/sessionless-header.e2e.ts @@ -30,7 +30,7 @@ describe('navigation without a selected Session', () => { } const tripwire = watchConsole(page) await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) - await page.getByRole('textbox', { name: 'Choose workspace', exact: true }).waitFor() + await page.getByRole('button', { name: 'Choose workspace', exact: true }).waitFor() const sessionHeader = page.locator('[data-slot="conversation.session.header"]') expect(await sessionHeader.count()).toBe(0) const header = page.locator('[data-slot="conversation.header"] > header') diff --git a/apps/web/tests/startup-rpc-budget.e2e.ts b/apps/web/tests/startup-rpc-budget.e2e.ts index f6655ffbf3..d8c89afcca 100644 --- a/apps/web/tests/startup-rpc-budget.e2e.ts +++ b/apps/web/tests/startup-rpc-budget.e2e.ts @@ -36,7 +36,7 @@ describe('startup RPC budget', () => { await page.goto(scaffold.authenticatedUrl) // Boot settles when the workspace picker is interactive; the trailing wait // absorbs the first-connection reset wave the budget must include. - await page.getByRole('textbox', { name: 'Choose workspace' }).waitFor({ timeout: 30_000 }) + await page.getByRole('button', { name: 'Choose workspace' }).waitFor({ timeout: 30_000 }) await page.waitForTimeout(3000) const describeCount = calls.filter(method => method === 'settings/describe').length expect(describeCount, `startup /api calls:\n${calls.join('\n')}`).toBe(DESCRIBE_BUDGET) diff --git a/apps/web/tests/support.ts b/apps/web/tests/support.ts index 884d648e8e..082f5019ae 100644 --- a/apps/web/tests/support.ts +++ b/apps/web/tests/support.ts @@ -122,7 +122,7 @@ export async function connectFreshWorkspace(page: Page, root: string, name = 'wo await pathInput.fill(join(root, name)) await pathInput.press('Enter') await dialog.getByRole('button', { name: 'Open', exact: true }).click() - await page.getByRole('treeitem', { name: 'New Session', exact: true }).waitFor({ timeout: 15_000 }) + await page.locator('[data-slot="conversation.session.header"]').waitFor({ state: 'attached', timeout: 15_000 }) await page.locator('[data-composer-input][contenteditable="true"][data-placeholder="Describe what you want to build, / commands, @ files or sessions"]') .waitFor({ timeout: 15_000 }) } @@ -146,7 +146,7 @@ export async function connectFreshWorkspaceZh(page: Page, root: string, name = ' await pathInput.fill(join(root, name)) await pathInput.press('Enter') await dialog.getByRole('button', { name: '打开', exact: true }).click() - await page.getByRole('treeitem', { name: '新会话', exact: true }).waitFor({ timeout: 15_000 }) + await page.locator('[data-slot="conversation.session.header"]').waitFor({ state: 'attached', timeout: 15_000 }) await page.locator('[data-composer-input][contenteditable="true"][data-placeholder="描述你想要构建的内容, / 调用指令, @ 文件或对话"]') .waitFor({ timeout: 15_000 }) } diff --git a/packages/client/ui-conversation/src/client/locales.ts b/packages/client/ui-conversation/src/client/locales.ts index c66fe10a8a..ecf2141f1d 100644 --- a/packages/client/ui-conversation/src/client/locales.ts +++ b/packages/client/ui-conversation/src/client/locales.ts @@ -22,6 +22,7 @@ export const zh = { 'placeholder.parentOffline': '父会话已离线,无法继续发送;仍可停止当前运行', 'placeholder.hero': '描述你想要构建的内容, / 调用指令, @ 文件或对话', 'placeholder.workspace': '选择一个工作区开始', + 'placeholder.preparing': '正在准备工作区…', 'placeholder.steerQueue': 'Cmd/Ctrl+Enter 插话发送全部排队消息', 'input.commands': '添加文件或调用指令', 'input.file': '文件', @@ -377,6 +378,7 @@ export const en = { 'placeholder.parentOffline': 'Parent session offline; sending is unavailable but you can still stop the run', 'placeholder.hero': 'Describe what you want to build, / commands, @ files or sessions', 'placeholder.workspace': 'Choose a workspace to start', + 'placeholder.preparing': 'Preparing workspace…', 'placeholder.steerQueue': 'Cmd/Ctrl+Enter steers all queued messages', 'input.commands': 'Add files or run commands', 'input.file': 'File', diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx index bf6456291f..82ea0e533d 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx @@ -143,7 +143,7 @@ export function ConversationContent(props: ConversationContentProps) { ...(inert ? { disabled: true, - placeholder: t('placeholder.workspace'), + placeholder: t(firstDraft.busy ? 'placeholder.preparing' : 'placeholder.workspace'), workspacePickerOpen: pickerOpen, ...(needsWorkspace ? { onRequestWorkspace: () => { setPickerOpen(true) } } : {}), } diff --git a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx index 25f7002ea4..619e3fddff 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -416,6 +416,7 @@ describe('ConversationRoot resident composer', () => { }) const box = b.view.getByRole('textbox') expect(box.getAttribute('aria-disabled')).toBe('true') + expect(box.getAttribute('aria-label')).toBe('正在准备工作区…') expect(box.getAttribute('aria-haspopup')).toBeNull() fireEvent.keyDown(box, { key: 'Enter' }) expect(b.sink).not.toHaveBeenCalled() diff --git a/snapshots/web/default-workspace/snapshot.yml b/snapshots/web/default-workspace/snapshot.yml index d1eed14d70..b9efb8a8b7 100644 --- a/snapshots/web/default-workspace/snapshot.yml +++ b/snapshots/web/default-workspace/snapshot.yml @@ -3,6 +3,8 @@ scenario: default-workspace profile: web composition: web-default recording: authored +workspace: + final: true header: class: web-default session: diff --git a/snapshots/web/default-workspace/workspace.expected/.empty b/snapshots/web/default-workspace/workspace.expected/.empty new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/snapshots/web/default-workspace/workspace.expected/.empty @@ -0,0 +1 @@ + From 8e313eaa306b38c35e57a9fd5a4d74174c0360b6 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 15:58:33 +0800 Subject: [PATCH 06/27] test(workspace): cover first-use configuration and preset failures --- .../api/workspace-controller/src/index.ts | 9 +++++--- .../tests/workspace-controller.host.spec.ts | 12 ++++++++-- .../tests/apply.client.spec.ts | 19 ++++++++++++---- .../tests/runtime.client.spec.tsx | 22 +++++++++++++++++++ 4 files changed, 53 insertions(+), 9 deletions(-) diff --git a/packages/api/workspace-controller/src/index.ts b/packages/api/workspace-controller/src/index.ts index 2281273e1e..966a5e9fb9 100644 --- a/packages/api/workspace-controller/src/index.ts +++ b/packages/api/workspace-controller/src/index.ts @@ -38,6 +38,9 @@ export interface Config { documentsLookupTimeoutMs?: number } +/** Directory policy after schema defaults have been applied. */ +type ResolvedConfig = Config & { documentsLookupTimeoutMs: number } + declare module '@deepseek-ai/cordis' { interface Context { /** Host Workspace business API and Remote namespace owner. */ @@ -49,12 +52,12 @@ declare module '@deepseek-ai/cordis' { export class WorkspaceController extends TypertRemoteService { static inject = ['typert', 'workspaceRegistry'] - static Config: z = z.object({ + static Config: z = z.object({ documentsDirectory: z.string(), documentsLookupTimeoutMs: z.natural().min(1).default(10_000), }) - private readonly config: Config + private readonly config: ResolvedConfig private readonly commands: WorkspaceCommands private readonly feed: WorkspaceFeed @@ -96,7 +99,7 @@ export class WorkspaceController extends TypertRemoteService { throw new RemoteError('gateway/bad-request', 'default Workspace requires a directory name and non-blank title', {}) } const workspace = await this.ctx.workspaceRegistry.initializeDefault(async () => { - const timeout = AbortSignal.timeout(this.config.documentsLookupTimeoutMs as number) + const timeout = AbortSignal.timeout(this.config.documentsLookupTimeoutMs) const path = await defaultWorkspaceDirectory( directoryName, this.config.documentsDirectory, AbortSignal.any([signal, timeout]), ) diff --git a/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts b/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts index ecaeb9a248..39cd085879 100644 --- a/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts +++ b/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts @@ -41,7 +41,7 @@ function deferred(): Deferred { return { promise, resolve } } -async function harness() { +async function harness(options: { systemDocuments?: boolean } = {}) { const root = realpathSync.native(mkdtempSync(join(tmpdir(), 'dsh-workspace-controller-'))) tempDirs.push(root) const ctx = new Context() @@ -59,7 +59,7 @@ async function harness() { lookups: { configure: () => dispose }, contexts: { configureHost: () => dispose }, } as never) - const controller = new WorkspaceController(ctx, { documentsDirectory: root }) + const controller = new WorkspaceController(ctx, options.systemDocuments === true ? {} : { documentsDirectory: root }) return { controller, ctx, root, storageDomain } } @@ -418,6 +418,14 @@ describe('WorkspaceController follow', () => { }) describe('first-use Remote', () => { + it('reuses an initialized Workspace without looking up system Documents', async () => { + const { controller, ctx, root } = await harness({ systemDocuments: true }) + const workspace = await ctx.workspaceRegistry.initializeDefault(async () => ({ path: root, title: 'Existing default' })) + const signal = AbortSignal.abort() + await expect(controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' }, signal)) + .resolves.toMatchObject({ workspace: { workspaceId: workspace!.id, path: root, title: 'Existing default' } }) + }) + it.each(['', ' ', '.', '..', '../outside', 'nested/name', 'nested\\name', 'C:outside', 'name\0', '.. ', 'tail.'])( 'rejects invalid directory name %j before invoking the registry', async (directoryName) => { const { controller, ctx } = await harness() diff --git a/packages/client/ui-agent-preset/tests/apply.client.spec.ts b/packages/client/ui-agent-preset/tests/apply.client.spec.ts index ea312699ce..378b40006f 100644 --- a/packages/client/ui-agent-preset/tests/apply.client.spec.ts +++ b/packages/client/ui-agent-preset/tests/apply.client.spec.ts @@ -6,7 +6,7 @@ */ import { Context } from '@deepseek-ai/cordis' -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it, onTestFinished, vi } from 'vitest' import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' @@ -76,6 +76,7 @@ async function bench(options: { failSettingsUpdate?: boolean selectGate?: Promise settingsRosterGate?: Promise + refuseSelect?: boolean } = {}) { const ctx = new Context() // The host's answer, mutable so a spec can move the default the way the @@ -153,7 +154,9 @@ async function bench(options: { deletePreset: () => Promise.resolve({ ok: true as const, value: undefined }), select: (_agentId: SessionId, agentPreset: string) => { calls.push(`select:${agentPreset}`) - return Promise.resolve(options.selectGate).then(() => ({ ok: true as const, value: agentPreset })) + return Promise.resolve(options.selectGate).then(() => options.refuseSelect === true + ? { ok: false as const, error: new RemoteError('gateway/internal', 'preset refused', {}) } + : { ok: true as const, value: agentPreset }) }, } ctx.provide('remote.agentPresets', agentPresets as never) @@ -715,8 +718,10 @@ describe('ui-agent-preset apply', () => { conversation() }) - it('applies the staged choice to the blank session the flow lands on', async () => { - const { ctx, slots, calls } = await bench() + it.each([false, true])('awaits the staged choice before first send and propagates refusal (%s)', async (refuseSelect) => { + const selection = Promise.withResolvers() + const { ctx, slots, calls } = await bench({ refuseSelect, selectGate: selection.promise }) + onTestFinished(async () => { selection.resolve(undefined); await ctx.fiber.dispose() }) declareRoot(slots) declareConversation(slots) ctx.provide('conversation', {} as never) @@ -736,6 +741,8 @@ describe('ui-agent-preset apply', () => { .inject as unknown as (sessionId?: SessionId) => AgentPresetSeatInjected const chip = injectSeat() + await ctx.serial('conversation/prepare-first-send', SessionId('absent')) + await chip.load() // Picked on the hero screen, where there is no session yet. await chip.select('minimal') @@ -747,6 +754,10 @@ describe('ui-agent-preset apply', () => { } sessions.notify() const bound = injectSeat(SessionId('s1')) + const preparing = ctx.serial('conversation/prepare-first-send', SessionId('s1')) + const settled = refuseSelect ? expect(preparing).rejects.toThrow('preset refused') : expect(preparing).resolves.toBeUndefined() + selection.resolve(undefined) + await settled await ctx.serial('conversation/prepare-first-send', SessionId('s1')) await bound.load() diff --git a/packages/test-support/client-runtime/tests/runtime.client.spec.tsx b/packages/test-support/client-runtime/tests/runtime.client.spec.tsx index 7d29ba7f72..aeff2554d1 100644 --- a/packages/test-support/client-runtime/tests/runtime.client.spec.tsx +++ b/packages/test-support/client-runtime/tests/runtime.client.spec.tsx @@ -557,6 +557,28 @@ describe('workspaces', () => { expect(view.container.textContent).toContain('ws:pending') await runtime.dispose() }) + it('requires an explicit default Workspace fixture and forwards its request and lifetime', async () => { + const runtime = await SlotTestRuntime.create() + try { + const request = { directoryName: 'default-workspace', title: 'Default workspace' } + const signal = new AbortController().signal + await expect(runtime.workspaces.initializeDefault(request, signal)).rejects.toThrow('requires a Workspace fixture') + const workspace = { + workspaceId: 'default' as WorkspaceId, title: request.title, path: '/default', sessionIds: [], + createdAt: '2026-09-20T00:00:00Z', updatedAt: '2026-09-20T00:00:00Z', + } + const initialize = vi.fn(async () => workspace) + runtime.workspaces.stub('initializeDefault', initialize) + await expect(runtime.workspaces.initializeDefault(request, signal)).resolves.toBe(workspace) + expect(initialize).toHaveBeenCalledWith(request, signal) + expect(runtime.workspaces.calls).toEqual([ + { method: 'initializeDefault', args: [request, signal] }, + { method: 'initializeDefault', args: [request, signal] }, + ]) + } finally { + await runtime.dispose() + } + }) }) describe('feature mount and disposal', () => { From d4d03b7c41ad12ea07254ca1ca9c170a476f8517 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 15:58:53 +0800 Subject: [PATCH 07/27] docs(workspace): clarify default directory lookup and cancellation --- .../feature/2026-09-20-default-workspace.i18n.yaml | 4 ++-- .../notes/implemented/feature/2026-09-20-default-workspace.md | 1 + .../implemented/feature/2026-09-20-default-workspace.zh.md | 1 + docs/subsystems/workspace.i18n.yaml | 4 ++-- docs/subsystems/workspace.md | 1 + docs/subsystems/workspace.zh.md | 1 + packages/api/workspace-controller/README.i18n.yaml | 4 ++-- packages/api/workspace-controller/README.md | 4 +++- packages/api/workspace-controller/README.zh.md | 4 +++- packages/api/workspace-controller/src/types.ts | 2 +- packages/extensions/tool-cordis/src/api-catalog.ts | 2 +- packages/workspace/workspace/README.i18n.yaml | 4 ++-- packages/workspace/workspace/README.md | 2 +- packages/workspace/workspace/README.zh.md | 2 +- packages/workspace/workspace/src/index.ts | 1 + 15 files changed, 23 insertions(+), 14 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml b/.agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml index cdb2673df8..a3ed2bee71 100644 --- a/.agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-20-default-workspace.md -2026-09-20-default-workspace.md: d2a32d47a407dcf211c1cad8bb98f29847a77a3b -2026-09-20-default-workspace.zh.md: 6b0ec542da6e9e4fe76fb56b6562edea9e5777f4 +2026-09-20-default-workspace.md: 376b2eaf7ac26c13e7483838700c88151b44135d +2026-09-20-default-workspace.zh.md: e16c5d47c6e1bceef293089edf882162812dfa1b diff --git a/.agents/notes/implemented/feature/2026-09-20-default-workspace.md b/.agents/notes/implemented/feature/2026-09-20-default-workspace.md index d2a32d47a4..376b2eaf7a 100644 --- a/.agents/notes/implemented/feature/2026-09-20-default-workspace.md +++ b/.agents/notes/implemented/feature/2026-09-20-default-workspace.md @@ -21,6 +21,7 @@ Creation failure preserves the draft and offers the existing folder picker. A su ## Alternatives considered - Creating on application startup would write directories for users who never send a message. +- Falling back to `/Documents` when system lookup is unavailable would choose an unverified Documents location; deployments that need another directory use the explicit Host override. - Inferring first use from visible sidebar rows would ignore archived, hidden, and cwd-less Sessions. - Using the localized path as the initialization marker would allow language changes or deletion to create another default. - Changing a Session's cwd after creation would change the meaning of its recorded tools and attachments. diff --git a/.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md b/.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md index 6b0ec542da..e16c5d47c6 100644 --- a/.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md +++ b/.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md @@ -21,6 +21,7 @@ Client 在发送时按其语言解析初始目录名和标题。Host 控制器 ## Alternatives considered - 在应用启动时创建,会为从未发送消息的用户写入目录。 +- 系统查询不可用时回退到 `/Documents`,会选择未经确认的 Documents 位置;需要其他目录的部署使用显式 Host 覆盖配置。 - 根据侧栏可见行推断首次使用,会忽略已归档、隐藏和无 cwd 的 Session。 - 将本地化路径作为初始化标记,会允许切换语言或删除后再次创建默认工作区。 - 在 Session 创建后更改 cwd,会改变其已记录工具和附件的含义。 diff --git a/docs/subsystems/workspace.i18n.yaml b/docs/subsystems/workspace.i18n.yaml index a7a3e3bb91..f9bef3d306 100644 --- a/docs/subsystems/workspace.i18n.yaml +++ b/docs/subsystems/workspace.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/workspace.md -workspace.md: b68acd965b55df462a0751d0b7e3230c82a62172 -workspace.zh.md: 074f59438eb16a4ffb1423540c3e1868857ae40f +workspace.md: 43a631ad0b04dd272436e272c931c2a16b7bbe88 +workspace.zh.md: c4571083f3e445828b4b3b41a27ed8abee9ee04d diff --git a/docs/subsystems/workspace.md b/docs/subsystems/workspace.md index b68acd965b..43a631ad0b 100644 --- a/docs/subsystems/workspace.md +++ b/docs/subsystems/workspace.md @@ -485,6 +485,7 @@ async create(path: string, title?: string): Promise * @param resolveDirectory - resolve the absolute directory and initial title; * called only for eligible creation, inside the registry mutation queue. * Missing directories are created recursively before registration. + * After resolution, caller cancellation does not roll back creation or registration. * @returns the initialized Workspace, or undefined when automatic creation is ineligible. */ initializeDefault(resolveDirectory: () => Promise<{ path: string; title: string }>): Promise diff --git a/docs/subsystems/workspace.zh.md b/docs/subsystems/workspace.zh.md index 074f59438e..c4571083f3 100644 --- a/docs/subsystems/workspace.zh.md +++ b/docs/subsystems/workspace.zh.md @@ -485,6 +485,7 @@ async create(path: string, title?: string): Promise * @param resolveDirectory - resolve the absolute directory and initial title; * called only for eligible creation, inside the registry mutation queue. * Missing directories are created recursively before registration. + * After resolution, caller cancellation does not roll back creation or registration. * @returns the initialized Workspace, or undefined when automatic creation is ineligible. */ initializeDefault(resolveDirectory: () => Promise<{ path: string; title: string }>): Promise diff --git a/packages/api/workspace-controller/README.i18n.yaml b/packages/api/workspace-controller/README.i18n.yaml index e7bc836965..6300d2f2e4 100644 --- a/packages/api/workspace-controller/README.i18n.yaml +++ b/packages/api/workspace-controller/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/api/workspace-controller/README.md -README.md: 275c51d0018dda5b2209cc7bece71b618e7d113d -README.zh.md: 92ca3f86f11ce77b51f834ce7c24f195095065b1 +README.md: 24bf0610689bfb857b24e7c8298b1b0494f1ca02 +README.zh.md: ca140abfdda246b62b0485e63ebfd05ab2efe6f9 diff --git a/packages/api/workspace-controller/README.md b/packages/api/workspace-controller/README.md index 275c51d001..24bf061068 100644 --- a/packages/api/workspace-controller/README.md +++ b/packages/api/workspace-controller/README.md @@ -29,7 +29,7 @@ The Client entry provides `ClientWorkspaceModel` and `createWorkspaceStateStream ### First-use Workspace -`workspace.initializeDefault({ directoryName, title })` returns the durable default Workspace; the Client service exposes the same request as `workspaces.initializeDefault(request, signal?)`. The [Conversation Client](../../client/ui-conversation/README.md) resolves these names from its send-time language. The Host places the directory under its account's `/deepseek-harness`, including on remote Web hosts. The directory name must be one non-blank segment without separators, colon, NUL, surrounding whitespace, or a trailing dot; the title must be non-blank. Linux system lookup requires `xdg-user-dir` with an enabled Documents directory. +`workspace.initializeDefault({ directoryName, title })` returns the durable default Workspace; the Client service exposes the same request as `workspaces.initializeDefault(request, signal?)`. The [Conversation Client](../../client/ui-conversation/README.md) resolves these names from its send-time language. The Host places the directory under its account's `/deepseek-harness`, including on remote Web hosts. The directory name must be one non-blank segment without separators, colon, NUL, surrounding whitespace, or a trailing dot; the title must be non-blank. OS filename restrictions also apply. Linux system lookup requires `xdg-user-dir` with an enabled Documents directory; hosts without it must configure `documentsDirectory` or use the folder picker. The [Workspace registry](../../workspace/workspace/README.md#first-use-workspace) owns eligibility, directory creation, and durable initialization. An existing default Workspace is returned without another Documents lookup; request names do not rename it. Invalid names or ineligible first use reject with `gateway/bad-request`; lookup and creation failures use standard Remote error handling. Initialization creates no Session and sends no message. @@ -38,6 +38,8 @@ The [Workspace registry](../../workspace/workspace/README.md#first-use-workspace | `documentsDirectory` | System Documents directory | Fully qualified Host directory override | | `documentsLookupTimeoutMs` | `10000` | Positive maximum duration of OS directory lookup, in milliseconds | +Documents lookup holds the registry mutation queue, so other Workspace mutations, including registration of a picked directory, can wait up to `documentsLookupTimeoutMs`. Cancellation can stop the lookup; after resolution succeeds, it does not roll back creation or registration. + ----- diff --git a/packages/api/workspace-controller/README.zh.md b/packages/api/workspace-controller/README.zh.md index 92ca3f86f1..ca140abfdd 100644 --- a/packages/api/workspace-controller/README.zh.md +++ b/packages/api/workspace-controller/README.zh.md @@ -29,7 +29,7 @@ Client 入口提供 `ClientWorkspaceModel` 和 `createWorkspaceStateStream()`。 ### 首次使用工作区 -`workspace.initializeDefault({ directoryName, title })` 返回持久化的默认工作区;Client service 通过 `workspaces.initializeDefault(request, signal?)` 提供同一请求。[Conversation Client](../../client/ui-conversation/README.zh.md)按发送时的语言解析这些名称。Host 将目录放在其账户的 `/deepseek-harness` 下,远程 Web Host 也遵循此规则。目录名必须是非空的单个片段,不能含分隔符、冒号、NUL、首尾空白或末尾句点;标题不能为空。Linux 系统查询要求存在 `xdg-user-dir` 且启用了 Documents 目录。 +`workspace.initializeDefault({ directoryName, title })` 返回持久化的默认工作区;Client service 通过 `workspaces.initializeDefault(request, signal?)` 提供同一请求。[Conversation Client](../../client/ui-conversation/README.zh.md)按发送时的语言解析这些名称。Host 将目录放在其账户的 `/deepseek-harness` 下,远程 Web Host 也遵循此规则。目录名必须是非空的单个片段,不能含分隔符、冒号、NUL、首尾空白或末尾句点;标题不能为空。操作系统的文件名限制同样适用。Linux 系统查询要求存在 `xdg-user-dir` 且启用了 Documents 目录;不具备该条件的 Host 必须配置 `documentsDirectory` 或使用文件夹选择器。 [Workspace 注册表](../../workspace/workspace/README.zh.md#first-use-workspace)负责资格判断、目录创建和持久化初始化。已有默认工作区直接返回,不再查询 Documents;请求中的名称不会将其重命名。名称无效或不满足首次使用条件时,以 `gateway/bad-request` 拒绝;查询和创建失败遵循标准 Remote 错误处理。初始化不创建 Session,也不发送消息。 @@ -38,6 +38,8 @@ Client 入口提供 `ClientWorkspaceModel` 和 `createWorkspaceStateStream()`。 | `documentsDirectory` | 系统 Documents 目录 | 完全限定的 Host 目录覆盖值 | | `documentsLookupTimeoutMs` | `10000` | 操作系统目录查询的正数最大时长,单位为毫秒 | +Documents 查询占用注册表变更队列,因此其他 Workspace 变更(包括登记已选目录)最多可能等待 `documentsLookupTimeoutMs`。取消可以停止查询;解析成功后,取消不会回滚创建或登记。 + ----- diff --git a/packages/api/workspace-controller/src/types.ts b/packages/api/workspace-controller/src/types.ts index e69c2b8c91..97188d9f23 100644 --- a/packages/api/workspace-controller/src/types.ts +++ b/packages/api/workspace-controller/src/types.ts @@ -56,7 +56,7 @@ export interface WorkspaceCreateRequest { /** Names chosen by the first-use Client before default Workspace initialization. */ export interface WorkspaceInitializeDefaultRequest { - /** Single non-blank name; no separators, colon, NUL, surrounding whitespace, or trailing dot. */ + /** Host rejects blank names, separators, colon, NUL, surrounding whitespace, and trailing dots; OS filename restrictions also apply. */ readonly directoryName: string /** Initial display title, retained across language changes. */ readonly title: string diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index eac1fcac40..b89f2f3ada 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -3376,7 +3376,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ { signature: 'initializeDefault(resolveDirectory: () => Promise<{ path: string; title: string }>): Promise', description: 'Initialize the default Workspace only while both the registry and Session history are empty. Repeated requests reuse its durable identity; deleting that registration permanently disables automatic creation.', - parameters: [{ name: 'resolveDirectory', description: 'resolve the absolute directory and initial title; called only for eligible creation, inside the registry mutation queue. Missing directories are created recursively before registration.' }], + parameters: [{ name: 'resolveDirectory', description: 'resolve the absolute directory and initial title; called only for eligible creation, inside the registry mutation queue. Missing directories are created recursively before registration. After resolution, caller cancellation does not roll back creation or registration.' }], returns: 'the initialized Workspace, or undefined when automatic creation is ineligible.', }, { diff --git a/packages/workspace/workspace/README.i18n.yaml b/packages/workspace/workspace/README.i18n.yaml index 43e9c7d159..7f50ab3f55 100644 --- a/packages/workspace/workspace/README.i18n.yaml +++ b/packages/workspace/workspace/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/workspace/workspace/README.md -README.md: f11d6496c04cf346c21f869e00ec5fb5526008db -README.zh.md: 3d458e13157bda612c3d33d0e7bfb57fa914e9b3 +README.md: 897aca8eb725bc9c3e0808e394e5c976886dd877 +README.zh.md: dc7a81340c9b134110975e700d43d5569fa6f03d diff --git a/packages/workspace/workspace/README.md b/packages/workspace/workspace/README.md index f11d6496c0..897aca8eb7 100644 --- a/packages/workspace/workspace/README.md +++ b/packages/workspace/workspace/README.md @@ -66,7 +66,7 @@ ctx.workspaceRegistry.list() // shows the project, newest first The directory resolver runs inside the mutation queue only when creation is eligible. It returns an absolute path and initial title; the registry creates missing parent directories, canonicalizes the path, rechecks Session history, and commits the Workspace with its initialization marker. An existing directory is reused; a file conflict or directory failure rejects initialization. The [Host controller](../../api/workspace-controller/README.md#first-use-workspace) supplies the Documents path policy. -The first successful registration records its identity durably. Repeated calls return it without resolving a directory again; renaming keeps that identity, and deleting its registration does not permit another automatic creation. Directory or registration failure leaves initialization unset for retry. Directories created before a later failure remain on disk. The [first-use decision](../../../.agents/notes/implemented/feature/2026-09-20-default-workspace.md) explains this lifetime. +The first successful registration records its identity durably. Repeated calls return it without resolving a directory again; renaming keeps that identity, and deleting its registration does not permit another automatic creation. Directory or registration failure leaves initialization unset for retry. Directories created before a later failure remain on disk. Once directory resolution succeeds, caller cancellation does not roll back directory creation or registration. The [first-use decision](../../../.agents/notes/implemented/feature/2026-09-20-default-workspace.md) explains this lifetime. ### Grouping sessions under a project diff --git a/packages/workspace/workspace/README.zh.md b/packages/workspace/workspace/README.zh.md index 3d458e1315..dc7a81340c 100644 --- a/packages/workspace/workspace/README.zh.md +++ b/packages/workspace/workspace/README.zh.md @@ -66,7 +66,7 @@ ctx.workspaceRegistry.list() // shows the project, newest first 目录解析器仅在允许创建时于变更队列内运行。它返回绝对路径和初始标题;注册表创建缺失的父目录、规范化路径、重新检查 Session 历史,再一起提交 Workspace 和初始化标记。已存在的目录直接复用;文件冲突或目录操作失败时拒绝初始化。[Host 控制器](../../api/workspace-controller/README.zh.md#first-use-workspace)提供 Documents 路径策略。 -首次成功登记会持久保存工作区身份。重复调用直接返回它,不再解析目录;改名保留该身份,删除登记也不会允许再次自动创建。目录或登记失败时,初始化状态保持未设置,可以重试。后续步骤失败前已创建的目录会保留在磁盘上。[首次使用决策](../../../.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md)说明这一生命周期。 +首次成功登记会持久保存工作区身份。重复调用直接返回它,不再解析目录;改名保留该身份,删除登记也不会允许再次自动创建。目录或登记失败时,初始化状态保持未设置,可以重试。后续步骤失败前已创建的目录会保留在磁盘上。目录解析成功后,调用方取消操作不会回滚目录创建或登记。[首次使用决策](../../../.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md)说明这一生命周期。 ### 将会话归入项目 diff --git a/packages/workspace/workspace/src/index.ts b/packages/workspace/workspace/src/index.ts index 6cb179022a..d0f3d3b8a5 100644 --- a/packages/workspace/workspace/src/index.ts +++ b/packages/workspace/workspace/src/index.ts @@ -182,6 +182,7 @@ export class WorkspaceRegistry extends Service { * @param resolveDirectory - resolve the absolute directory and initial title; * called only for eligible creation, inside the registry mutation queue. * Missing directories are created recursively before registration. + * After resolution, caller cancellation does not roll back creation or registration. * @returns the initialized Workspace, or undefined when automatic creation is ineligible. */ initializeDefault(resolveDirectory: () => Promise<{ path: string; title: string }>): Promise { From 4d2e420ef852578770b9fb72dddcb2dcba85a236 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 17:19:54 +0800 Subject: [PATCH 08/27] refactor(workspace): initialize the default workspace on startup --- ...ession-scope-and-provide-channel.i18n.yaml | 4 +- ...lient-session-scope-and-provide-channel.md | 9 +- ...nt-session-scope-and-provide-channel.zh.md | 9 +- .../2026-09-20-default-workspace.i18n.yaml | 4 +- .../feature/2026-09-20-default-workspace.md | 12 +- .../2026-09-20-default-workspace.zh.md | 12 +- apps/web/tests/README.i18n.yaml | 4 +- apps/web/tests/README.md | 2 + apps/web/tests/README.zh.md | 2 + apps/web/tests/default-workspace.e2e.ts | 199 +++++++++--------- .../default-workspace/preparing.expected.md | 7 - apps/web/tests/scaffold.ts | 8 +- docs/subsystems/workspace.i18n.yaml | 4 +- docs/subsystems/workspace.md | 6 +- docs/subsystems/workspace.zh.md | 6 +- .../api/workspace-controller/README.i18n.yaml | 4 +- packages/api/workspace-controller/README.md | 4 +- .../api/workspace-controller/README.zh.md | 4 +- .../workspace-controller/src/client/model.ts | 6 +- .../src/client/service.ts | 8 +- .../api/workspace-controller/src/index.ts | 11 +- .../tests/model.client.spec.ts | 4 + .../tests/transport.client.spec.ts | 12 ++ .../tests/workspace-controller.host.spec.ts | 10 +- .../client/ui-agent-preset/README.i18n.yaml | 4 +- packages/client/ui-agent-preset/README.md | 2 - packages/client/ui-agent-preset/README.zh.md | 2 - .../ui-agent-preset/src/client/index.ts | 8 - .../ui-agent-preset/src/client/seat-store.ts | 13 +- .../tests/apply.client.spec.ts | 52 +---- .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 6 +- packages/client/ui-conversation/README.zh.md | 6 +- .../ui-conversation/src/client/apply.ts | 43 ++-- .../src/client/contract/input.ts | 6 - .../src/client/contract/slots.ts | 13 +- .../ui-conversation/src/client/index.ts | 8 - .../src/client/input/facade.ts | 4 +- .../src/client/input/first-draft.ts | 82 -------- .../ui-conversation/src/client/locales.ts | 10 - .../client/skeleton/ConversationContent.tsx | 42 ++-- .../src/client/skeleton/ConversationRoot.tsx | 5 +- .../src/client/skeleton/InputBar.tsx | 81 ++++--- .../tests/apply-inject.client.spec.tsx | 111 +--------- .../tests/assembly-surfaces.client.spec.tsx | 22 +- .../tests/first-draft.client.spec.ts | 141 ------------- .../tests/input-bar.client.spec.tsx | 1 - .../tests/input-matrix.client.spec.tsx | 1 - .../tests/input-scenarios.client.spec.tsx | 1 - .../tests/skeleton.client.spec.tsx | 17 -- packages/client/ui-workspace/README.i18n.yaml | 4 +- packages/client/ui-workspace/README.md | 4 +- packages/client/ui-workspace/README.zh.md | 4 +- .../src/client/WorkspacePicker.tsx | 48 +++-- .../ui-workspace/src/client/contract/slots.ts | 8 +- .../client/ui-workspace/src/client/index.ts | 3 +- .../client/ui-workspace/src/client/locales.ts | 8 + .../ui-workspace/src/client/navigation.ts | 56 +++-- .../tests/workspace-picker.client.spec.tsx | 35 ++- .../tests/workspaces-service.client.spec.ts | 115 +++++++--- .../extensions/tool-cordis/src/api-catalog.ts | 6 +- .../client-runtime/src/workspaces.ts | 9 +- .../tests/runtime.client.spec.tsx | 4 +- scripts/gen-cordis-catalog.ts | 1 - 64 files changed, 509 insertions(+), 832 deletions(-) delete mode 100644 apps/web/tests/expected/default-workspace/preparing.expected.md delete mode 100644 packages/client/ui-conversation/src/client/input/first-draft.ts delete mode 100644 packages/client/ui-conversation/tests/first-draft.client.spec.ts diff --git a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.i18n.yaml index 8790781b63..da98873480 100644 --- a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.md -2026-07-25-web-client-session-scope-and-provide-channel.md: f1e83e8b38561d5edd3bf6a212aa2bd4ac5028f8 -2026-07-25-web-client-session-scope-and-provide-channel.zh.md: 6eea0af064caf976774ae2bb2992fd6651daf695 +2026-07-25-web-client-session-scope-and-provide-channel.md: 76561bc0e330b3e3a26607569ae327217d0a0b67 +2026-07-25-web-client-session-scope-and-provide-channel.zh.md: d5d92b2ca53ba78929dd8591a6ded7028e4fed24 diff --git a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.md b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.md index f1e83e8b38..76561bc0e3 100644 --- a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.md +++ b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.md @@ -26,8 +26,8 @@ The reference-owned lifetime and Provider targeting now follow [Client Session r Host-side `session.create(workspaceId)` produces Session + Agent + cwd in one piece (an atomic bundle, never split); the client side is the mirror of that birth — the instant a session row enters the list mirror, the client mints its Agent scope (actx + provide + the full input surface mounted): - Session identity is the host's true form from birth: the sessionId arrives via the `session.create` response / the `host/session-added` frame, and every client-side address (the scope tag, slot store keys, RPC addressing) uses that same id. -- A manual Workspace pick or successful [first-use default preparation](../feature/2026-09-20-default-workspace.md) establishes cwd before the client calls `session.create({workspaceId})` and receives the complete entity. -- "New Session with no workspace picked" has no Session or scope entity. The composer retains a local text draft; Session-scoped slash commands become available after connection. +- A manual Workspace pick or successful [first-use startup initialization](../feature/2026-09-20-default-workspace.md) establishes cwd before the client calls `session.create({workspaceId})` and receives the complete entity. +- "New Session with no workspace picked" is a **pure view state** (a navigation position) corresponding to no session/scope entity; until the pick, the composer is locked whole (no slash, no plain text). - A "blank session" is an ordinary materialized session with no turn yet; to Agent-scope plugins on the host (goal/plan/skill/…) it remains an ordinary Session, so slash/plan are naturally live. ### Agent scope: the actx is the sole session carrier in the client-side cordis world @@ -95,7 +95,7 @@ Slot scope is the closed set `root | session-maybe | session`: - `session-maybe` inherits the nearest `SessionProvider` binding with ADOPTION identity: an incarnation born Session-less keeps its React instance when that Provider receives its first binding, then remounts when the Provider switches generation or returns to absence. Component-local per-Session state clears when the Provider switches generation. Across a switch, only persisted Store values survive generation retirement; binding-owned sources survive only when another reference keeps that generation alive. With no binding, `sessionId`, the results of `useSession`/`useInput`, and `inputActions` may all be absent. Provider-roster changes rematerialize the mounted binding without changing its identity, while the per-entry adoption bookkeeping lives in the renderer's `SessionMaybeEntry`. - `session` guarantees that `sessionId`, every hook source, and every prop exist; each strict entry's error boundary is keyed by `sessionId`, so switching sessions recreates that entry and its session store. -`conversation` is the resident `session-maybe` shell under its owning `SessionProvider`: `ConversationRoot`, HeroShell, the Workspace picker, the scrollport and composer stack, and the overlay chain's fallback frame retain their React instances across the no-Session → blank-Session switch. Two strict entries fill fixed regions without reparenting that tree: `conversation.session.header` carries breadcrumb/tabs/actions above the scrollport, while `conversation.session` carries the view ring and draft mirror inside it; both share the same Session-scoped chat store. The composer bar (`conversation.composer.bar`) is itself `session-maybe`: before a Session exists, its injected editor retains the first-use text draft; after connection, the same InputBar instance receives the retained Session's input. The remaining input slots stay strict `session` and dispatch nothing until then. The blank → engaging/active transition never rebuilds the InputBar on a phase flip. +`conversation` is the resident `session-maybe` shell under its owning `SessionProvider`: `ConversationRoot`, HeroShell, the Workspace picker, the scrollport and composer stack, and the overlay chain's fallback frame retain their React instances across the no-Session → blank-Session switch. Two strict entries fill fixed regions without reparenting that tree: `conversation.session.header` carries breadcrumb/tabs/actions above the scrollport, while `conversation.session` carries the view ring and draft mirror inside it; both share the same Session-scoped chat store. The composer bar (`conversation.composer.bar`) is itself `session-maybe`: with no Session its machine faces and message actions are inert, while the whole dashed card opens the existing Workspace picker by pointer and its read-only textarea does the same through Enter or Space. The same instance — textarea included — goes live when a binding appears; the remaining input slots stay strict `session` and dispatch nothing until then. The blank → engaging/active transition never rebuilds the InputBar on a phase flip. Blank Sessions retain the header's leading and corner slots so navigation controls, including the right-sidebar opener, are available before the first message. Title, actions, utilities, and View tabs remain hidden in the blank phase. The header still requires a selected Session; the Files and Terminal entries use that Session's workspace and execution services without requiring a recorded Turn. @@ -136,5 +136,6 @@ Blank Sessions retain the header's leading and corner slots so navigation contro - Plugins gain session context isomorphic to the host's: per-session state hangs on the actx and mounts/tears down in one piece with the scope fiber, making leaks structurally impossible; two-session isolation is structurally guaranteed by the scope filter. - The client object layer converges to a wire mirror: session identity, lifecycle, and capability adjudication all defer to the host entity — the input system (the next layer) always faces a session with a real Agent, and providers like slash/skill uniformly address by sessionId directly. - Blank-session governance takes zero dedicated mechanisms: state rides one derived bit, visibility rides the unified list projection (only the current blank shows, as `New Session`), reuse acquires the persisted writer, and the ordinary ceiling rides same-Workspace reuse. The accepted/running display memory that guards the conversion is Client-local. -- The cost: the id→ctx handoff discipline and provide's Concurrent discipline are conventions rather than type-enforced, pinned by review and tests. Session-scoped input remains unavailable until a Session exists; the [resident conversation shell](../../../../packages/client/ui-conversation/README.md) owns the local first-use draft during that interval. + +- The cost: the id→ctx handoff discipline and provide's Concurrent discipline are conventions rather than type-enforced, pinned by review and tests. The single state axis still withholds machine faces until a Session exists; the [resident conversation shell](../../../../packages/client/ui-conversation/README.md) routes activation to the Workspace picker during that interval. - Known gaps: approval/question recovery across prune (TODO); model selection returns in live-mutation shape (the host `selectModel` trio is ready-made, its client consumer not yet built). diff --git a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md index 6eea0af064..d5d92b2ca5 100644 --- a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md @@ -26,8 +26,8 @@ web client 只有一张全局会话面:slot 全部从根上下文渲染,插 host 侧 `session.create(workspaceId)` 一体产出 Session + Agent + cwd(作为不可拆分的原子整体);client 侧就是这次出生的镜像——会话行进入 list mirror 的瞬间,client 为它铸 Agent scope(actx + provide + 输入面全套挂上): - 会话身份自出生即为 host 真身:sessionId 由 `session.create` 响应 / `host/session-added` 帧带来,client 侧一切寻址(scope tag、slot store 键、RPC 地址)用的都是同一个 id。 -- 手动选择 Workspace 或成功[准备首次使用默认工作区](../feature/2026-09-20-default-workspace.zh.md)先确定 cwd,client 随后调用 `session.create({workspaceId})` 并取得完整实体。 -- 「New Session 且未选 workspace」没有 Session 或 scope 实体。Composer 保留本地文本草稿;连接后才提供 Session scope 的 slash 命令。 +- 手动选定 Workspace 或完成[首次使用的启动初始化](../feature/2026-09-20-default-workspace.zh.md) 后,cwd 已确定,client 再调 `session.create({workspaceId})`,拿到完整实体。 +- 「New Session 且未选 workspace」是**纯视图态**(一个导航位置),不对应任何会话/scope 实体;选定之前 composer 整体锁死(无 slash、无纯文本)。 - 「空会话」是尚无轮次的普通实体化会话;对 host 上的 Agent-scope 插件(goal/plan/skill(技能)/…)而言,它仍是普通 Session,因此 slash/plan 自然可用。 ### Agent scope:actx 是 client 侧 cordis 世界的唯一会话载体 @@ -95,7 +95,7 @@ slot scope 是闭集 `root | session-maybe | session`: - `session-maybe` 以**收养(adoption)身份语义**继承最近 `SessionProvider` 的 binding:空态出生的化身在该 Provider 第一次收到 binding 时保持 React 实例,此后 Provider 切换 generation 或回到空态时重挂。Provider 切换 generation 时,组件本地的逐 Session 状态会清零。切换过程中,只有持久化 Store 值能活过 generation 退休;只有另一份 reference 保活该 generation 时,binding 自有 source 才能保留。无 binding 时,`sessionId`、`useSession`/`useInput` 的结果与 `inputActions` 均可缺省。Provider roster 变化会重新物化已挂载 binding,但不改变其 identity;逐 entry 的收养记账住在 renderer 的 `SessionMaybeEntry`。 - `session` 保证 `sessionId`、所有钩子 source 与 props 均存在;每个严格 entry 的错误边界以 `sessionId` 为 key,切换会话会重建该 entry 及其会话 store。 -`conversation` 是其 owner `SessionProvider` 下的 `session-maybe` 常驻外壳:`ConversationRoot`、HeroShell、Workspace picker、scrollport 与 composer stack,以及 overlay chain 的 fallback 外框,在无 Session → blank Session 的切换中保持 React 实例。两个严格 session entry 只填入固定区域,不改变该树的父级:`conversation.session.header` 在 scrollport 上方承载 breadcrumb/tab/action,`conversation.session` 在其内部承载 view ring 与 draft mirror;二者共享同一个 Session scope chat store。composer bar(`conversation.composer.bar`)本身即为 `session-maybe`:Session 存在前,注入的编辑器保存首次使用文本草稿;连接后,同一 InputBar 实例接收已持有 Session 的输入。其余输入 slot 保持严格 `session`,在此之前不派发任何内容。blank → engaging/active 的 InputBar 不因 phase 翻转而重建。 +`conversation` 是其 owner `SessionProvider` 下的 `session-maybe` 常驻外壳:`ConversationRoot`、HeroShell、Workspace picker、scrollport 与 composer stack,以及 overlay chain 的 fallback 外框,在无 Session → blank Session 的切换中保持 React 实例。两个严格 session entry 只填入固定区域,不改变该树的父级:`conversation.session.header` 在 scrollport 上方承载 breadcrumb/tab/action,`conversation.session` 在其内部承载 view ring 与 draft mirror;二者共享同一个 Session scope chat store。composer bar(`conversation.composer.bar`)本身即为 `session-maybe`:无 Session 时,其 machine faces 和消息动作保持惰性,整张虚线卡片可经指针打开现有 Workspace picker,只读 textarea 也可通过 Enter 或 Space 打开。binding 出现后同一实例(含 textarea)转为 live;其余输入 slot 保持严格 `session`,在此之前不派发任何内容。blank → engaging/active 的 InputBar 不因 phase 翻转而重建。 blank Session 保留 header 的 leading 与 corner slot,让右侧栏展开入口等导航控件在首条消息之前即可使用。标题、actions、utilities 和 View tabs 在 blank phase 中继续隐藏。header 仍要求已选中的 Session;Files 与 Terminal 入口使用该 Session 的工作区和执行服务,无需已有 Turn 记录。 @@ -136,5 +136,6 @@ blank Session 保留 header 的 leading 与 corner slot,让右侧栏展开入 - 插件获得与 host 同构的会话上下文:逐会话状态挂 actx、随 scope fiber 一次拆装,泄漏结构性不可能;双会话隔离由 scope filter 结构性保证。 - client 对象层收敛为 wire 镜像:会话身份、生命周期、能力判别全部以 host 实体为准——输入体系(下一层)面对的永远是「有真 Agent 的会话」,slash/skill 等提供方一律以 sessionId 直接寻址。 - 空会话治理零专用机制:状态靠一个派生位,可见性靠统一列表投影(仅 current blank 以 `New Session` 展示),复用时获取持久化写锁,常规上限靠同 Workspace 复用。转正所依赖的受理/运行展示记忆仅保留在客户端。 -- 代价:id→ctx 换乘纪律、provide 的 Concurrent 纪律都是约定而非类型强制,靠 review 与测试钉住。Session 存在前,其 scope 输入仍不可用;这段时间内,[常驻会话壳](../../../../packages/client/ui-conversation/README.zh.md)负责本地首次使用草稿。 + +- 代价:id→ctx 换乘纪律、provide 的 Concurrent 纪律都是约定而非类型强制,靠 review 与测试钉住。单一状态轴仍会在 Session 存在前隐藏 machine face;这段时间内,[常驻会话壳](../../../../packages/client/ui-conversation/README.zh.md)会把激活操作转到 Workspace picker。 - 已知欠账:approval/question 跨 prune 恢复(TODO);模型选择以 live-mutation 形状回归(host `selectModel` 三件套现成,其 client 消费方尚未构建)。 diff --git a/.agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml b/.agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml index a3ed2bee71..89b4d5dabf 100644 --- a/.agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-20-default-workspace.md -2026-09-20-default-workspace.md: 376b2eaf7ac26c13e7483838700c88151b44135d -2026-09-20-default-workspace.zh.md: e16c5d47c6e1bceef293089edf882162812dfa1b +2026-09-20-default-workspace.md: 1674079403b17fb1bd984052a85975609179cad0 +2026-09-20-default-workspace.zh.md: 81a7c96efa3d8b8d4673b684b59babe339706f29 diff --git a/.agents/notes/implemented/feature/2026-09-20-default-workspace.md b/.agents/notes/implemented/feature/2026-09-20-default-workspace.md index 376b2eaf7a..1674079403 100644 --- a/.agents/notes/implemented/feature/2026-09-20-default-workspace.md +++ b/.agents/notes/implemented/feature/2026-09-20-default-workspace.md @@ -10,17 +10,17 @@ A new installation requires a directory choice before the user can send a first ## Decision -The conversation shell retains an unsent local text draft without creating a Session. Its first send asks the Host to prepare a default Workspace, then connects a real Session and submits through the ordinary composer pipeline. The first-use draft awaits staged mode selection before automatic submission. This partially supersedes the locked no-Session composer in [Session scope and provisioning](../architecture/2026-07-25-web-client-session-scope-and-provide-channel.md); that note still owns blank-Session reuse and provisioning rationale. +Startup waits for complete Workspace and Session baselines. When both lists are empty, the Client asks the Host to prepare the default Workspace, then creates or reuses and selects its blank Session. Input stays unavailable until a Session exists and uses the ordinary composer pipeline thereafter. [Session scope and provisioning](../architecture/2026-07-25-web-client-session-scope-and-provide-channel.md) owns blank-Session reuse and provisioning rationale. The [Workspace registry](../../../../packages/workspace/workspace/README.md#first-use-workspace) owns eligibility and directory preparation. All live Sessions, persisted headers, and archived identities count, including entries absent from the sidebar. The operation shares the registry mutation queue and rechecks Session history after directory preparation because Sessions can start independently. -The Client resolves the initial directory name and title from its language when sending. The Host controller resolves the Documents location; the registry receives a directory resolver with no locale dependency. The resolver runs inside the mutation queue only for eligible creation, so repeated requests reuse the durable Workspace without another OS lookup. A durable Workspace id records successful initialization independently of that name. Renaming, changing language, restarting, or deleting the registration cannot initialize another default. The marker commits with the registration, so a failed registration can retry. Directory contents remain subject to the existing [metadata-only deletion policy](2026-07-27-workspace-registration-deletion.md). +The Client resolves the initial directory name and title from its language at startup. The Host controller resolves the Documents location; the registry receives a directory resolver with no locale dependency. The resolver runs inside the mutation queue only for eligible creation, so repeated requests reuse the durable Workspace without another OS lookup. A durable Workspace id records successful initialization independently of that name. Renaming, changing language, restarting, or deleting the registration cannot initialize another default. The marker commits with the registration, so a failed registration can retry. Directory contents remain subject to the existing [metadata-only deletion policy](2026-07-27-workspace-registration-deletion.md). -Creation failure preserves the draft and offers the existing folder picker. A successful registration survives Session creation or prompt failure. Picking a folder after failure transfers the text without sending it; a later send remains the user's action. +Ineligible first use returns no Workspace without a failure dialog. Preparation failure offers the existing folder picker; startup does not retry on later list notifications. A successful registration survives Session creation or prompt failure. Selecting either the default or a manually picked Workspace never submits a message. ## Alternatives considered -- Creating on application startup would write directories for users who never send a message. +- Creating only when sending avoids unused directories but requires a separate local draft, transfer into a Session, and coordination of the first submission. Startup creation accepts the early filesystem effect and uses ordinary Session input throughout. - Falling back to `/Documents` when system lookup is unavailable would choose an unverified Documents location; deployments that need another directory use the explicit Host override. - Inferring first use from visible sidebar rows would ignore archived, hidden, and cwd-less Sessions. - Using the localized path as the initialization marker would allow language changes or deletion to create another default. @@ -28,6 +28,6 @@ Creation failure preserves the draft and offers the existing folder picker. A su ## Consequences -First-use typing has no Host Session or filesystem effects. Preparation remains a Host responsibility for both Desktop and remote Web clients, so remote users use the Host account's Documents location. Unavailable Documents lookup fails with the same folder-selection recovery as directory creation failure. +Opening a new installation can create a directory and blank Session before the user sends a message. Directory authorization and preparation failures can appear during startup. Preparation remains a Host responsibility for both Desktop and remote Web clients, so remote users use the Host account's Documents location. Unavailable Documents lookup fails with the same folder-selection recovery as directory creation failure. -The feature preserves [reference-owned Client Session lifetimes](../architecture/2026-09-15-client-session-references.md) and requires no agent-loop or Session-event change. Registry and client tests cover retries, hidden history, concurrency, and draft recovery; the [browser scenario](../../../../apps/web/tests/default-workspace.e2e.ts) verifies the assembled first-send and picker paths with an isolated Documents directory and recorded Session replay. +The feature preserves [reference-owned Client Session lifetimes](../architecture/2026-09-15-client-session-references.md) and requires no agent-loop or Session-event change. Registry and client tests cover retries, hidden history, concurrency, and startup cancellation; the [browser scenario](../../../../apps/web/tests/default-workspace.e2e.ts) verifies the assembled startup, reload, first-send, and picker paths with an isolated Documents directory and recorded Session replay. diff --git a/.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md b/.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md index e16c5d47c6..81a7c96efa 100644 --- a/.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md +++ b/.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md @@ -10,17 +10,17 @@ Status: implemented ## Decision -会话外壳保存未发送的本地文本草稿,不创建 Session。首次发送请求 Host 准备默认 Workspace,随后连接真实 Session,并通过常规 composer 流程提交。首次使用的草稿会在自动提交前等待暂存的模式选择完成。这部分取代[Session scope 与供给通道](../architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md)中无 Session 时锁定 composer 的决策;该记录仍负责 blank Session 复用与供给通道的理由。 +启动时等待完整的 Workspace 和 Session 基线。两份列表均为空时,Client 请求 Host 准备默认 Workspace,随后创建或复用并选中其空白 Session。Session 存在前不可输入,之后使用常规 composer 流程。[Session scope 与供给通道](../architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md)负责 blank Session 复用与供给通道的理由。 [Workspace registry](../../../../packages/workspace/workspace/README.zh.md#first-use-workspace)负责资格判断和目录准备。所有 live Session、持久化 header 和已归档身份都计入判断,包括侧栏中不可见的条目。操作共用 registry 修改队列,并在目录准备后重新检查 Session 历史,因为 Session 可以独立启动。 -Client 在发送时按其语言解析初始目录名和标题。Host 控制器解析 Documents 位置;注册表接收不依赖 locale 的目录解析器。解析器仅在允许创建时于变更队列内运行,因此重复请求直接复用持久化的 Workspace,无需再次查询操作系统目录。持久化 Workspace id 独立于名称记录初始化成功。改名、切换语言、重启或删除登记均不能再次初始化默认工作区。标记与登记一起提交,因此登记失败可以重试。目录内容仍遵循已有的[仅删除元数据策略](2026-07-27-workspace-registration-deletion.zh.md)。 +Client 在启动时按其语言解析初始目录名和标题。Host 控制器解析 Documents 位置;注册表接收不依赖 locale 的目录解析器。解析器仅在允许创建时于变更队列内运行,因此重复请求直接复用持久化的 Workspace,无需再次查询操作系统目录。持久化 Workspace id 独立于名称记录初始化成功。改名、切换语言、重启或删除登记均不能再次初始化默认工作区。标记与登记一起提交,因此登记失败可以重试。目录内容仍遵循已有的[仅删除元数据策略](2026-07-27-workspace-registration-deletion.zh.md)。 -创建失败时保留草稿,并提供现有文件夹选择器。成功的登记会在 Session 创建或提示词发送失败后保留。失败后选择文件夹只转移文本,不发送;随后发送仍由用户操作。 +不符合首次使用条件时不返回 Workspace,也不显示失败弹窗。准备失败时提供现有文件夹选择器;后续列表通知不会触发启动流程重试。成功的登记会在 Session 创建或提示词发送失败后保留。选中默认或手动选择的 Workspace 均不会提交消息。 ## Alternatives considered -- 在应用启动时创建,会为从未发送消息的用户写入目录。 +- 仅在发送时创建可以避免未使用的目录,但需要独立的本地草稿、向 Session 转移草稿及首次提交协调逻辑。启动时创建接受提前写入文件系统的副作用,始终使用普通 Session 输入。 - 系统查询不可用时回退到 `/Documents`,会选择未经确认的 Documents 位置;需要其他目录的部署使用显式 Host 覆盖配置。 - 根据侧栏可见行推断首次使用,会忽略已归档、隐藏和无 cwd 的 Session。 - 将本地化路径作为初始化标记,会允许切换语言或删除后再次创建默认工作区。 @@ -28,6 +28,6 @@ Client 在发送时按其语言解析初始目录名和标题。Host 控制器 ## Consequences -首次使用时输入文本不会产生 Host Session 或文件系统副作用。Desktop 和远程 Web 客户端均由 Host 准备目录,因此远程用户使用 Host 账户的 Documents 位置。Documents 查询不可用时,采用与目录创建失败相同的文件夹选择恢复路径。 +打开新安装的应用即可在用户发送消息前创建目录和空白 Session。目录授权与准备失败提示可能在启动期间出现。Desktop 和远程 Web 客户端均由 Host 准备目录,因此远程用户使用 Host 账户的 Documents 位置。Documents 查询不可用时,采用与目录创建失败相同的文件夹选择恢复路径。 -该功能保留[由引用持有的 Client Session 生命周期](../architecture/2026-09-15-client-session-references.zh.md),无需修改 agent-loop 或 Session 事件。Registry 和客户端测试覆盖重试、隐藏历史、并发及草稿恢复;[浏览器场景](../../../../apps/web/tests/default-workspace.e2e.ts)通过隔离的 Documents 目录和已录制 Session 回放验证完整装配下的首次发送与选择器路径。 +该功能保留[由引用持有的 Client Session 生命周期](../architecture/2026-09-15-client-session-references.zh.md),无需修改 agent-loop 或 Session 事件。Registry 和客户端测试覆盖重试、隐藏历史、并发及启动取消;[浏览器场景](../../../../apps/web/tests/default-workspace.e2e.ts)通过隔离的 Documents 目录和已录制 Session 回放验证完整装配下的启动、刷新、首次发送与选择器路径。 diff --git a/apps/web/tests/README.i18n.yaml b/apps/web/tests/README.i18n.yaml index cf707e6cb3..4d920402fa 100644 --- a/apps/web/tests/README.i18n.yaml +++ b/apps/web/tests/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write apps/web/tests/README.md -README.md: b2fa27bb7a60ed78309bf81e77b9cd5217bbee2a -README.zh.md: 29ae2e86018257a4fc2379ea2563c8b5e5e9036f +README.md: 8b9c58ce9e4cf2f5f6978c0c6eb5517fe000d3d2 +README.zh.md: 199ae3b56166aa2ffa1c0bed9a16b844ffd7b74f diff --git a/apps/web/tests/README.md b/apps/web/tests/README.md index b2fa27bb7a..8b9c58ce9e 100644 --- a/apps/web/tests/README.md +++ b/apps/web/tests/README.md @@ -4,6 +4,8 @@ English | [中文](README.zh.md) These tests boot the real web composition in-process and drive it with a real Chromium over real HTTP. The lane's mechanics — modes, fixtures, goldens, and the deliberate composition divergences from `dsh web` — are documented in [`scaffold.ts`](scaffold.ts) and the [browser e2e Agent Note](../../../.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md). +Ordinary scenarios begin with no registered Workspace or Session and a durable marker recording a removed default Workspace, so explicit folder-selection scenarios retain control of their cwd. `launchWebScaffold({ firstUse: true })` leaves initialization eligible for startup scenarios. + ## Completion observations State-sensitive cases use Workspace, admission, attachment, and model-stream barriers to separate visible intermediate states from completed operations. Details close waits for frame transitions; archive verification assigns an explicit title to the seeded Session and follows that identity across reload. See the [CI fixture synchronization decision](../../../.agents/notes/implemented/testing/2026-09-08-ci-completion-observations.md). diff --git a/apps/web/tests/README.zh.md b/apps/web/tests/README.zh.md index 29ae2e8601..199ae3b561 100644 --- a/apps/web/tests/README.zh.md +++ b/apps/web/tests/README.zh.md @@ -4,6 +4,8 @@ 这些测试在进程内启动真实的 web 组合,并用真实 Chromium 通过真实 HTTP 驱动它。该 lane 的运行机制——模式、fixture(测试前置数据)、golden,以及与 `dsh web` 之间刻意保留的组合差异——记录在 [`scaffold.ts`](scaffold.ts) 和 [浏览器 e2e Agent Note](../../../.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md) 中。 +普通场景以没有已登记 Workspace 或 Session、但持久化标记记录默认 Workspace 已被删除的状态启动,使显式文件夹选择场景自行决定 cwd。`launchWebScaffold({ firstUse: true })` 保留初始化资格,供启动场景使用。 + ## 完成状态观察 依赖状态的用例使用 Workspace、接纳、附件和模型流屏障,区分可见中间状态与已完成操作。详情关闭等待框架过渡结束;归档验证为 seed Session 设置显式标题,并跨重载跟踪该身份。参见 [CI fixture 同步决策](../../../.agents/notes/implemented/testing/2026-09-08-ci-completion-observations.zh.md)。 diff --git a/apps/web/tests/default-workspace.e2e.ts b/apps/web/tests/default-workspace.e2e.ts index 265fa715b2..d3b6db624d 100644 --- a/apps/web/tests/default-workspace.e2e.ts +++ b/apps/web/tests/default-workspace.e2e.ts @@ -1,9 +1,9 @@ -/** First-use messages prepare a durable Workspace through the shipped Web composition. */ +/** First-use startup prepares a durable Workspace through the shipped Web composition. */ import { mkdir, readFile, stat, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { chromium } from 'playwright' -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it, onTestFinished } from 'vitest' import { assertFinalWorkspaceSnapshot, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, launchWebScaffold, selectedSessionFixture, watchConsole, webSnapshotMode, @@ -13,124 +13,125 @@ import { newEnglishPage, saveFailureShot } from './support.ts' const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/fresh-round-trip/session.v3.jsonl', import.meta.url)) const EXPECTED = fileURLToPath(new URL('../../../snapshots/web/default-workspace/ui.expected.md', import.meta.url)) const FAILURE_EXPECTED = fileURLToPath(new URL('./expected/default-workspace/failure.expected.md', import.meta.url)) -const PREPARING_EXPECTED = fileURLToPath(new URL('./expected/default-workspace/preparing.expected.md', import.meta.url)) const MODE = webSnapshotMode() describe.skipIf(MODE === 'record')('web e2e: default Workspace', () => { - it('sends the first draft in a newly selected default Workspace and keeps its identity across reload', async () => { + it('prepares a blank Session on startup, reuses it after reload, and sends through the ordinary composer', async () => { const fixture = await selectedSessionFixture(FIXTURE) const scaffold = await launchWebScaffold({ + firstUse: true, replayFixture: fixture, // The shared recording remains read-only; replay compares the complete persisted Session. compareReplaySession: MODE === 'replay', paceMs: 5, }) + onTestFinished(() => scaffold.close()) + const browser = await chromium.launch() try { - const browser = await chromium.launch() + const page = await newEnglishPage(browser) + const tripwire = watchConsole(page) try { - const page = await newEnglishPage(browser) - const tripwire = watchConsole(page) - try { - await page.goto(scaffold.authenticatedUrl) - const input = page.locator('[data-composer-input][contenteditable="true"]').first() - await input.waitFor() - const prompt = fixtureUserPrompts(await readFile(fixture, 'utf8'))[0]! - await input.fill(prompt) - expect(scaffold.ctx.workspaceRegistry.list()).toEqual([]) - expect(scaffold.ctx.sessions.list()).toEqual([]) - const settled = scaffold.whenTurnSettled() - const preparing = Promise.withResolvers() - const initialize = scaffold.ctx.workspaceRegistry.initializeDefault.bind(scaffold.ctx.workspaceRegistry) - vi.spyOn(scaffold.ctx.workspaceRegistry, 'initializeDefault').mockImplementationOnce(async (resolve) => { - await preparing.promise - return initialize(resolve) - }) - try { - await input.press('Enter') - await page.getByRole('textbox', { name: 'Preparing workspace…', exact: true }).waitFor() - await compareOrRefreshGolden(PREPARING_EXPECTED, await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd), MODE) - } finally { - preparing.resolve(undefined) - } - const sessionId = await settled - const workspace = scaffold.ctx.workspaceRegistry.list()[0]! - expect(workspace.title).toBe('Default workspace') - expect(workspace.path).toBe(join(scaffold.workspaceCwd, 'Documents', 'deepseek-harness', 'Default workspace')) - expect((await stat(workspace.path)).isDirectory()).toBe(true) - expect(workspace.sessionIds).toContain(sessionId) - expect(scaffold.ctx.sessions.get(sessionId)?.header.cwd).toBe(workspace.path) - await assertFinalWorkspaceSnapshot(fileURLToPath(new URL('../../../snapshots/web/default-workspace', import.meta.url)), workspace.path) - await page.getByText('DONE', { exact: true }).waitFor() - await compareOrRefreshGolden(EXPECTED, await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd), MODE) - await page.reload() - await page.getByText('DONE', { exact: true }).waitFor() - expect(scaffold.ctx.workspaceRegistry.list().map(item => item.id)).toEqual([workspace.id]) - expect(tripwire.pageErrors).toEqual([]) - expect(tripwire.warnings).toEqual([]) - } catch (error) { - await saveFailureShot(page, 'web-e2e-default-workspace') - throw error - } - } finally { - await browser.close() + await page.goto(scaffold.authenticatedUrl) + const input = page.locator('[data-composer-input][contenteditable="true"]').first() + await input.waitFor() + expect(scaffold.ctx.workspaceRegistry.list()).toHaveLength(1) + const initialSession = scaffold.ctx.sessions.list()[0]! + expect(scaffold.ctx.sessions.list()).toHaveLength(1) + expect(initialSession.snapshotEvents().some(event => event.type === 'user/message')).toBe(false) + await page.reload() + await input.waitFor() + expect(scaffold.ctx.sessions.list().map(session => session.id)).toEqual([initialSession.id]) + const prompt = fixtureUserPrompts(await readFile(fixture, 'utf8'))[0]! + await input.fill(prompt) + const settled = scaffold.whenTurnSettled() + await input.press('Enter') + const sessionId = await settled + const workspace = scaffold.ctx.workspaceRegistry.list()[0]! + expect(workspace.title).toBe('Default workspace') + expect(workspace.path).toBe(join(scaffold.workspaceCwd, 'Documents', 'deepseek-harness', 'Default workspace')) + expect((await stat(workspace.path)).isDirectory()).toBe(true) + expect(workspace.sessionIds).toContain(sessionId) + expect(scaffold.ctx.sessions.get(sessionId)?.header.cwd).toBe(workspace.path) + await assertFinalWorkspaceSnapshot(fileURLToPath(new URL('../../../snapshots/web/default-workspace', import.meta.url)), workspace.path) + await page.getByText('DONE', { exact: true }).waitFor() + await compareOrRefreshGolden(EXPECTED, await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd), MODE) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + } catch (error) { + await saveFailureShot(page, 'web-e2e-default-workspace') + throw error } } finally { - await scaffold.close() + await browser.close() } }) - it('keeps the draft on a directory conflict and opens the composed folder picker for recovery', async () => { - const scaffold = await launchWebScaffold() + it('reports a startup directory conflict and opens the composed folder picker for recovery', async () => { + const scaffold = await launchWebScaffold({ firstUse: true }) + onTestFinished(() => scaffold.close()) + const parent = join(scaffold.workspaceCwd, 'Documents', 'deepseek-harness') + await mkdir(parent, { recursive: true }) + await writeFile(join(parent, '默认工作区'), 'occupied') + const chosen = join(scaffold.workspaceCwd, 'chosen') + await mkdir(chosen) + const browser = await chromium.launch() try { - const parent = join(scaffold.workspaceCwd, 'Documents', 'deepseek-harness') - await mkdir(parent, { recursive: true }) - await writeFile(join(parent, '默认工作区'), 'occupied') - const chosen = join(scaffold.workspaceCwd, 'chosen') - await mkdir(chosen) - const browser = await chromium.launch() + const page = await browser.newPage({ locale: 'zh-CN', timezoneId: 'Asia/Shanghai' }) + const tripwire = watchConsole(page) try { - const page = await browser.newPage({ locale: 'zh-CN', timezoneId: 'Asia/Shanghai' }) - const tripwire = watchConsole(page) - try { - await page.goto(scaffold.authenticatedUrl) - const input = page.locator('[data-composer-input][contenteditable="true"]').first() - await input.fill('保留这条消息') - await input.press('Enter') - const modal = page.getByRole('dialog', { name: '无法创建默认工作区' }) - await modal.waitFor() - await expect.poll(() => input.textContent()).toBe('保留这条消息') - expect(scaffold.ctx.workspaceRegistry.list()).toEqual([]) - expect(scaffold.ctx.sessions.list()).toEqual([]) - await compareOrRefreshGolden(FAILURE_EXPECTED, await modal.ariaSnapshot(), MODE) - await modal.getByRole('button', { name: '取消', exact: true }).click() - expect(await input.textContent()).toBe('保留这条消息') - await input.press('Enter') - await modal.getByRole('button', { name: '选择文件夹', exact: true }).click() - const picker = page.getByRole('dialog', { name: '选择工作区目录' }) - await picker.waitFor() - await picker.getByRole('button', { name: '编辑路径', exact: true }).click() - await picker.getByRole('textbox', { name: '编辑路径' }).fill(chosen) - await page.keyboard.press('Enter') - await picker.getByRole('button', { name: '打开', exact: true }).click() - await picker.waitFor({ state: 'hidden' }) - await expect.poll(() => scaffold.ctx.workspaceRegistry.list().length).toBe(1) - await page.getByRole('treeitem', { name: '新会话', exact: true }).waitFor() - await expect.poll(() => input.textContent()).toBe('保留这条消息') - expect(scaffold.ctx.workspaceRegistry.list()[0]?.path).toBe(chosen) - expect(scaffold.ctx.sessions.list()).toHaveLength(1) - expect(scaffold.ctx.sessions.list().every(session => - session.snapshotEvents().every(event => event.type !== 'user/message'))).toBe(true) - expect(tripwire.pageErrors).toEqual([]) - expect(tripwire.warnings).toEqual([]) - } catch (error) { - await saveFailureShot(page, 'web-e2e-default-workspace-failure') - throw error - } - } finally { - await browser.close() + await page.goto(scaffold.authenticatedUrl) + const input = page.locator('[data-composer-input][contenteditable="true"]').first() + const modal = page.getByRole('dialog', { name: '无法创建默认工作区' }) + await modal.waitFor() + expect(scaffold.ctx.workspaceRegistry.list()).toEqual([]) + expect(scaffold.ctx.sessions.list()).toEqual([]) + await compareOrRefreshGolden(FAILURE_EXPECTED, await modal.ariaSnapshot(), MODE) + await modal.getByRole('button', { name: '取消', exact: true }).click() + expect(await input.count()).toBe(0) + await page.reload() + await modal.waitFor() + await modal.getByRole('button', { name: '选择文件夹', exact: true }).click() + const picker = page.getByRole('dialog', { name: '选择工作区目录' }) + await picker.waitFor() + await picker.getByRole('button', { name: '编辑路径', exact: true }).click() + await picker.getByRole('textbox', { name: '编辑路径' }).fill(chosen) + await page.keyboard.press('Enter') + await picker.getByRole('button', { name: '打开', exact: true }).click() + await picker.waitFor({ state: 'hidden' }) + await expect.poll(() => scaffold.ctx.workspaceRegistry.list().length).toBe(1) + await input.waitFor() + expect(await input.textContent()).toBe('') + expect(scaffold.ctx.workspaceRegistry.list()[0]?.path).toBe(chosen) + expect(scaffold.ctx.sessions.list()).toHaveLength(1) + expect(scaffold.ctx.sessions.list().every(session => + session.snapshotEvents().every(event => event.type !== 'user/message'))).toBe(true) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + } catch (error) { + await saveFailureShot(page, 'web-e2e-default-workspace-failure') + throw error } } finally { - await scaffold.close() + await browser.close() + } + }) + + it('keeps an explicitly deleted default absent on startup', async () => { + const scaffold = await launchWebScaffold() + onTestFinished(() => scaffold.close()) + const browser = await chromium.launch() + try { + const page = await newEnglishPage(browser) + const attempted = page.waitForResponse(response => response.url().includes('/api/workspace/initializeDefault')) + await page.goto(scaffold.authenticatedUrl) + expect((await attempted).ok()).toBe(true) + await page.getByRole('button', { name: 'Choose workspace', exact: true }).waitFor() + expect(await page.getByRole('dialog', { name: 'Unable to create default workspace' }).count()).toBe(0) + expect(await page.locator('[data-composer-input][contenteditable="true"]').count()).toBe(0) + expect(scaffold.ctx.workspaceRegistry.list()).toEqual([]) + expect(scaffold.ctx.sessions.list()).toEqual([]) + } finally { + await browser.close() } }) }) diff --git a/apps/web/tests/expected/default-workspace/preparing.expected.md b/apps/web/tests/expected/default-workspace/preparing.expected.md deleted file mode 100644 index 09e86fbb6e..0000000000 --- a/apps/web/tests/expected/default-workspace/preparing.expected.md +++ /dev/null @@ -1,7 +0,0 @@ -- banner -- text: Into the Unknown Preview -- button "Choose workspace" -- button "Standard mode" -- textbox "Preparing workspace…" [disabled] -- button "Add files or run commands" [disabled] -- button "Send message" [disabled] diff --git a/apps/web/tests/scaffold.ts b/apps/web/tests/scaffold.ts index f903205c80..16a80f5dd2 100644 --- a/apps/web/tests/scaffold.ts +++ b/apps/web/tests/scaffold.ts @@ -395,6 +395,8 @@ export interface LaunchOptions { deepSeekMessages?: boolean /** Leave the current welcome notice pending; ordinary scenarios pre-acknowledge it before browser boot. */ welcomeNoticePending?: boolean + /** Leave first-use Workspace initialization eligible; ordinary scenarios start after the default was removed. */ + firstUse?: boolean /** * Patch the shipped DeepSeek search row to a deterministic endpoint and * credential reference. Browser search scenarios keep the real provider and @@ -600,7 +602,7 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise ({ path: workspaceCwd, title: 'Workspace' })) + if (initial !== undefined) await ctx.workspaceRegistry.delete(initial.id) + } const boundPort = ctx.get('webServer')?.port if (boundPort === undefined) { throw new Error('web e2e scaffold: webServer service missing after settled boot') diff --git a/docs/subsystems/workspace.i18n.yaml b/docs/subsystems/workspace.i18n.yaml index f9bef3d306..452d200cf5 100644 --- a/docs/subsystems/workspace.i18n.yaml +++ b/docs/subsystems/workspace.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/workspace.md -workspace.md: 43a631ad0b04dd272436e272c931c2a16b7bbe88 -workspace.zh.md: c4571083f3e445828b4b3b41a27ed8abee9ee04d +workspace.md: 323323946ac92bbc03962b83c5e77a81a960d89a +workspace.zh.md: aedd1134305aaa7e97ccd449631ff72446bf28b4 diff --git a/docs/subsystems/workspace.md b/docs/subsystems/workspace.md index 43a631ad0b..323323946a 100644 --- a/docs/subsystems/workspace.md +++ b/docs/subsystems/workspace.md @@ -306,12 +306,12 @@ Host service backing the generated `ctx.remote.workspace` namespace. @Remote('create') create(request: WorkspaceCreateRequest): Promise /** - * Initialize or reuse the default Workspace before the first user message. + * Initialize or reuse the default Workspace during first-use startup. * @param request - initial directory name and title; never rename an existing default. * @param signal - caller lifetime; cancels native directory lookup. - * @returns the durable Workspace without creating a Session or sending a message. + * @returns the durable Workspace, or undefined when first-use initialization is ineligible; creates no Session or message. */ -@Remote('initializeDefault') async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise +@Remote('initializeDefault') async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise /** * Rename one Workspace to a unique non-blank title. diff --git a/docs/subsystems/workspace.zh.md b/docs/subsystems/workspace.zh.md index c4571083f3..aedd113430 100644 --- a/docs/subsystems/workspace.zh.md +++ b/docs/subsystems/workspace.zh.md @@ -306,12 +306,12 @@ Host service backing the generated `ctx.remote.workspace` namespace. @Remote('create') create(request: WorkspaceCreateRequest): Promise /** - * Initialize or reuse the default Workspace before the first user message. + * Initialize or reuse the default Workspace during first-use startup. * @param request - initial directory name and title; never rename an existing default. * @param signal - caller lifetime; cancels native directory lookup. - * @returns the durable Workspace without creating a Session or sending a message. + * @returns the durable Workspace, or undefined when first-use initialization is ineligible; creates no Session or message. */ -@Remote('initializeDefault') async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise +@Remote('initializeDefault') async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise /** * Rename one Workspace to a unique non-blank title. diff --git a/packages/api/workspace-controller/README.i18n.yaml b/packages/api/workspace-controller/README.i18n.yaml index 6300d2f2e4..0520266936 100644 --- a/packages/api/workspace-controller/README.i18n.yaml +++ b/packages/api/workspace-controller/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/api/workspace-controller/README.md -README.md: 24bf0610689bfb857b24e7c8298b1b0494f1ca02 -README.zh.md: ca140abfdda246b62b0485e63ebfd05ab2efe6f9 +README.md: 27053331007681eb373b4537514bbe701dad660d +README.zh.md: d0726496de5dcf623fedb531ad988b3c608fc2ac diff --git a/packages/api/workspace-controller/README.md b/packages/api/workspace-controller/README.md index 24bf061068..2705333100 100644 --- a/packages/api/workspace-controller/README.md +++ b/packages/api/workspace-controller/README.md @@ -29,9 +29,9 @@ The Client entry provides `ClientWorkspaceModel` and `createWorkspaceStateStream ### First-use Workspace -`workspace.initializeDefault({ directoryName, title })` returns the durable default Workspace; the Client service exposes the same request as `workspaces.initializeDefault(request, signal?)`. The [Conversation Client](../../client/ui-conversation/README.md) resolves these names from its send-time language. The Host places the directory under its account's `/deepseek-harness`, including on remote Web hosts. The directory name must be one non-blank segment without separators, colon, NUL, surrounding whitespace, or a trailing dot; the title must be non-blank. OS filename restrictions also apply. Linux system lookup requires `xdg-user-dir` with an enabled Documents directory; hosts without it must configure `documentsDirectory` or use the folder picker. +`workspace.initializeDefault({ directoryName, title })` returns the durable default Workspace; the Client service exposes the same request as `workspaces.initializeDefault(request, signal?)`. The [Workspace Client](../../client/ui-workspace/README.md) resolves these names from its startup language. The Host places the directory under its account's `/deepseek-harness`, including on remote Web hosts. The directory name must be one non-blank segment without separators, colon, NUL, surrounding whitespace, or a trailing dot; the title must be non-blank. OS filename restrictions also apply. Linux system lookup requires `xdg-user-dir` with an enabled Documents directory; hosts without it must configure `documentsDirectory` or use the folder picker. -The [Workspace registry](../../workspace/workspace/README.md#first-use-workspace) owns eligibility, directory creation, and durable initialization. An existing default Workspace is returned without another Documents lookup; request names do not rename it. Invalid names or ineligible first use reject with `gateway/bad-request`; lookup and creation failures use standard Remote error handling. Initialization creates no Session and sends no message. +The [Workspace registry](../../workspace/workspace/README.md#first-use-workspace) owns eligibility, directory creation, and durable initialization. An existing default Workspace is returned without another Documents lookup; request names do not rename it. Ineligible first use returns `undefined`, so startup can leave directory selection to the user. Invalid names reject with `gateway/bad-request`; lookup and creation failures use standard Remote error handling. Initialization creates no Session and sends no message. | Configuration | Default | Purpose | | --- | --- | --- | diff --git a/packages/api/workspace-controller/README.zh.md b/packages/api/workspace-controller/README.zh.md index ca140abfdd..d0726496de 100644 --- a/packages/api/workspace-controller/README.zh.md +++ b/packages/api/workspace-controller/README.zh.md @@ -29,9 +29,9 @@ Client 入口提供 `ClientWorkspaceModel` 和 `createWorkspaceStateStream()`。 ### 首次使用工作区 -`workspace.initializeDefault({ directoryName, title })` 返回持久化的默认工作区;Client service 通过 `workspaces.initializeDefault(request, signal?)` 提供同一请求。[Conversation Client](../../client/ui-conversation/README.zh.md)按发送时的语言解析这些名称。Host 将目录放在其账户的 `/deepseek-harness` 下,远程 Web Host 也遵循此规则。目录名必须是非空的单个片段,不能含分隔符、冒号、NUL、首尾空白或末尾句点;标题不能为空。操作系统的文件名限制同样适用。Linux 系统查询要求存在 `xdg-user-dir` 且启用了 Documents 目录;不具备该条件的 Host 必须配置 `documentsDirectory` 或使用文件夹选择器。 +`workspace.initializeDefault({ directoryName, title })` 返回持久化的默认工作区;Client service 通过 `workspaces.initializeDefault(request, signal?)` 提供同一请求。[Workspace Client](../../client/ui-workspace/README.zh.md)按启动时的语言解析这些名称。Host 将目录放在其账户的 `/deepseek-harness` 下,远程 Web Host 也遵循此规则。目录名必须是非空的单个片段,不能含分隔符、冒号、NUL、首尾空白或末尾句点;标题不能为空。操作系统的文件名限制同样适用。Linux 系统查询要求存在 `xdg-user-dir` 且启用了 Documents 目录;不具备该条件的 Host 必须配置 `documentsDirectory` 或使用文件夹选择器。 -[Workspace 注册表](../../workspace/workspace/README.zh.md#first-use-workspace)负责资格判断、目录创建和持久化初始化。已有默认工作区直接返回,不再查询 Documents;请求中的名称不会将其重命名。名称无效或不满足首次使用条件时,以 `gateway/bad-request` 拒绝;查询和创建失败遵循标准 Remote 错误处理。初始化不创建 Session,也不发送消息。 +[Workspace 注册表](../../workspace/workspace/README.zh.md#first-use-workspace)负责资格判断、目录创建和持久化初始化。已有默认工作区直接返回,不再查询 Documents;请求中的名称不会将其重命名。不满足首次使用条件时返回 `undefined`,启动流程可将目录选择留给用户。名称无效时以 `gateway/bad-request` 拒绝;查询和创建失败遵循标准 Remote 错误处理。初始化不创建 Session,也不发送消息。 | 配置 | 默认值 | 用途 | | --- | --- | --- | diff --git a/packages/api/workspace-controller/src/client/model.ts b/packages/api/workspace-controller/src/client/model.ts index 3f6dda9f76..25a84d655e 100644 --- a/packages/api/workspace-controller/src/client/model.ts +++ b/packages/api/workspace-controller/src/client/model.ts @@ -108,9 +108,11 @@ export class ClientWorkspaceModel implements WorkspaceFollowSink { * @param signal - caller lifetime. * @returns generated Remote result. */ - async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise> { + async initializeDefault( + request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal, + ): Promise> { const result = await this.remote.initializeDefault(request, signal) - if (result.ok) this.upsert(result.value.workspace) + if (result.ok && result.value !== undefined) this.upsert(result.value.workspace) return result } diff --git a/packages/api/workspace-controller/src/client/service.ts b/packages/api/workspace-controller/src/client/service.ts index f94baafdb2..393fed0b7f 100644 --- a/packages/api/workspace-controller/src/client/service.ts +++ b/packages/api/workspace-controller/src/client/service.ts @@ -43,9 +43,9 @@ export interface IWorkspaces { * Initialize or reuse the default Workspace. * @param request - initial directory name and title. * @param signal - caller lifetime. - * @returns the prepared Workspace; rejects when directory selection is required. + * @returns the prepared Workspace, or undefined when first-use initialization is ineligible; rejects on preparation failure. */ - initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise + initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise /** * Rename a Workspace. * @param workspaceId - target Workspace. @@ -117,10 +117,10 @@ export class WorkspaceController extends Service implements IWorkspaces { return result.value.workspace } - async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise { + async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise { const result = await this.model.initializeDefault(request, signal) if (!result.ok) throw new WorkspaceCreateError(result.error) - return result.value.workspace + return result.value?.workspace } async rename(workspaceId: WorkspaceId, title: string): Promise { diff --git a/packages/api/workspace-controller/src/index.ts b/packages/api/workspace-controller/src/index.ts index 966a5e9fb9..7a63e5b699 100644 --- a/packages/api/workspace-controller/src/index.ts +++ b/packages/api/workspace-controller/src/index.ts @@ -86,13 +86,13 @@ export class WorkspaceController extends TypertRemoteService { } /** - * Initialize or reuse the default Workspace before the first user message. + * Initialize or reuse the default Workspace during first-use startup. * @param request - initial directory name and title; never rename an existing default. * @param signal - caller lifetime; cancels native directory lookup. - * @returns the durable Workspace without creating a Session or sending a message. + * @returns the durable Workspace, or undefined when first-use initialization is ineligible; creates no Session or message. */ @Remote('initializeDefault') - async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise { + async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise { const { directoryName, title } = request if (directoryName.trim() === '' || directoryName !== directoryName.trim() || directoryName.endsWith('.') || /[/\\:\0]/.test(directoryName) || title.trim() === '') { @@ -105,10 +105,7 @@ export class WorkspaceController extends TypertRemoteService { ) return { path, title } }) - if (workspace === undefined) { - throw new RemoteError('gateway/bad-request', 'choose a directory to create a Workspace', {}) - } - return { workspace: workspaceView(workspace) } + return workspace === undefined ? undefined : { workspace: workspaceView(workspace) } } /** diff --git a/packages/api/workspace-controller/tests/model.client.spec.ts b/packages/api/workspace-controller/tests/model.client.spec.ts index 4558d4f64d..e4f11a7678 100644 --- a/packages/api/workspace-controller/tests/model.client.spec.ts +++ b/packages/api/workspace-controller/tests/model.client.spec.ts @@ -177,6 +177,10 @@ describe('ClientWorkspaceModel', () => { expect(remote.initializeDefault).toHaveBeenCalledWith({ directoryName: '默认工作区', title: '默认工作区' }, signal) expect(model.getSnapshot().items.map(item => item.workspaceId)).toEqual(['default']) const before = model.getSnapshot() + remote.initializeDefault.mockResolvedValueOnce(remoteOk(undefined)) + await expect(model.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' })) + .resolves.toEqual({ ok: true, value: undefined }) + expect(model.getSnapshot()).toBe(before) remote.initializeDefault.mockResolvedValueOnce(workspaceError( new RemoteError('gateway/bad-request', 'choose a folder', {}), )) diff --git a/packages/api/workspace-controller/tests/transport.client.spec.ts b/packages/api/workspace-controller/tests/transport.client.spec.ts index 9829004125..220f83e069 100644 --- a/packages/api/workspace-controller/tests/transport.client.spec.ts +++ b/packages/api/workspace-controller/tests/transport.client.spec.ts @@ -310,6 +310,18 @@ describe('Workspace state stream', () => { }) describe('WorkspaceController', () => { + it('returns no Workspace when startup is ineligible without changing the list', async ({ mock, start }) => { + const { remote, client } = await gatewayClient(mock, start) + const model = new ClientWorkspaceModel(remote.workspace) + model.replaceBaseline({ items: [], archivedSessionIds: [], pinnedSessionIds: [] }) + const controller = new WorkspaceController(client.ctx, model) + const before = model.getSnapshot() + mock.remote.workspace.initializeDefault.mockResolvedValueOnce({ ok: true, value: undefined }) + await expect(controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' })) + .resolves.toBeUndefined() + expect(model.getSnapshot()).toBe(before) + }) + it('publishes the model source and exposes successful Workspace commands', async ({ mock, start }) => { const { remote, client } = await gatewayClient(mock, start) const model = new ClientWorkspaceModel(remote.workspace) diff --git a/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts b/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts index 39cd085879..0656aaf8bf 100644 --- a/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts +++ b/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts @@ -447,24 +447,24 @@ describe('first-use Remote', () => { it('uses the requested display title independently of the directory name', async () => { const { controller, root } = await harness() const result = await controller.initializeDefault({ directoryName: 'default-workspace', title: 'Default workspace' }, new AbortController().signal) - expect(result.workspace).toMatchObject({ path: join(root, 'deepseek-harness', 'default-workspace'), title: 'Default workspace' }) + expect(result?.workspace).toMatchObject({ path: join(root, 'deepseek-harness', 'default-workspace'), title: 'Default workspace' }) }) it('returns a durable Workspace without allocating a Session', async () => { const { controller, ctx, root } = await harness() const signal = new AbortController().signal const result = await controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' }, signal) - expect(result.workspace.path).toBe(join(root, 'deepseek-harness', 'Default workspace')) - expect(existsSync(result.workspace.path)).toBe(true) + expect(result!.workspace.path).toBe(join(root, 'deepseek-harness', 'Default workspace')) + expect(existsSync(result!.workspace.path)).toBe(true) expect(ctx.sessions.list()).toEqual([]) expect(await controller.initializeDefault({ directoryName: '默认工作区', title: '默认工作区' }, signal)).toEqual(result) }) - it('rejects ineligible first use and propagates preparation failures', async () => { + it('skips ineligible first use and propagates preparation failures', async () => { const { controller, ctx, root } = await harness() await ctx.workspaceRegistry.create(root) await expect(controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' }, new AbortController().signal)) - .rejects.toMatchObject({ code: 'gateway/bad-request' }) + .resolves.toBeUndefined() vi.spyOn(ctx.workspaceRegistry, 'initializeDefault').mockRejectedValueOnce(new Error('permission denied')) await expect(controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' }, new AbortController().signal)) .rejects.toThrow('permission denied') diff --git a/packages/client/ui-agent-preset/README.i18n.yaml b/packages/client/ui-agent-preset/README.i18n.yaml index 9a9afcdd63..3b67b4ca8a 100644 --- a/packages/client/ui-agent-preset/README.i18n.yaml +++ b/packages/client/ui-agent-preset/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-agent-preset/README.md -README.md: 5545dbbddf18d6f181d5e8c17e194043b3e0bf9d -README.zh.md: 4ef159280dd5e72c9d12aa75905855a2b9bf8d27 +README.md: 5f2c9acaa5840e71d6ca237c5fc5eccb52724cda +README.zh.md: 5c61823c25f145c0e516f3f2a16c2de05c250ef1 diff --git a/packages/client/ui-agent-preset/README.md b/packages/client/ui-agent-preset/README.md index 5545dbbddf..5f2c9acaa5 100644 --- a/packages/client/ui-agent-preset/README.md +++ b/packages/client/ui-agent-preset/README.md @@ -49,8 +49,6 @@ The settings section writes the Host's existing `agent-presets` namespace throug The chip follows the preset projection of its bound Session while its plugin and Provider generation remain active. Settings synchronization creates the same bound controller when needed, even before the chip mounts. A late projection or another client's preset update refreshes the display without submitting a selection; list notifications do not repeat an in-flight selection. Settings changes wait for that selection and recheck the captured blank Session before applying. A choice staged during a pending request remains available afterward. -After preparing a default Workspace, the first-use draft waits for the staged preset through `conversation/prepare-first-send`. Concurrent `apply()` calls wait for the active selection without repeating it. A refusal keeps the unsent Session draft. - ----- diff --git a/packages/client/ui-agent-preset/README.zh.md b/packages/client/ui-agent-preset/README.zh.md index 4ef159280d..5c61823c25 100644 --- a/packages/client/ui-agent-preset/README.zh.md +++ b/packages/client/ui-agent-preset/README.zh.md @@ -49,8 +49,6 @@ kind: "package-reference" 只要插件及 Provider generation 仍有效,选择芯片就会跟随其绑定 Session 的预设投影。即使选择芯片尚未挂载,设置同步也会按需创建同一个绑定控制器。延后到达的投影或其他客户端的预设更新会刷新显示,而不会提交选择;列表通知不会重复仍在进行中的选择操作。设置修改会等待该操作结束,并在应用之前重新检查已捕获的空白 Session。请求期间暂存的新选择会保留。 -默认工作区准备完成后,首次使用的草稿通过 `conversation/prepare-first-send` 等待暂存的模式选择。并发的 `apply()` 调用等待已有选择操作,不会重复提交。选择被拒绝时保留未发送的 Session 草稿。 - ----- diff --git a/packages/client/ui-agent-preset/src/client/index.ts b/packages/client/ui-agent-preset/src/client/index.ts index 113e440900..0838fd89aa 100644 --- a/packages/client/ui-agent-preset/src/client/index.ts +++ b/packages/client/ui-agent-preset/src/client/index.ts @@ -143,14 +143,6 @@ export function apply(ctx: ClientContext): void { // render and simply hides the button while no flow exists. let creatorDraft: (() => void) | undefined ctx.inject(['slots', 'conversation', 'sessions', 'uiWorkspace'], (scope: ClientContext) => { - scope.on('conversation/prepare-first-send', async (sessionId) => { - const binding = scope.sessions.binding(sessionId) - if (binding === undefined) return - const seat = seatFor(binding) - if (staged.id === undefined && !seat.store.getSnapshot().busy) return - const error = await seat.apply() - if (error !== undefined) throw new Error(error) - }) const seatInjected = (sessionId: SessionId | undefined): AgentPresetSeatInjected => { const binding = sessionId === undefined ? undefined : ctx.sessions.binding(sessionId) const seat = binding === undefined ? unboundSeat : seatFor(binding) diff --git a/packages/client/ui-agent-preset/src/client/seat-store.ts b/packages/client/ui-agent-preset/src/client/seat-store.ts index 4e7488bc3b..45bd9373e4 100644 --- a/packages/client/ui-agent-preset/src/client/seat-store.ts +++ b/packages/client/ui-agent-preset/src/client/seat-store.ts @@ -193,18 +193,11 @@ export class AgentPresetSeatController { * * Called both by `select()` and by whoever observes the current session * changing, because the session may appear either before or after the pick. - * Concurrent callers wait for the active selection without repeating it. - * @returns the Host refusal, or undefined when successful or no switch starts. + * List updates do not repeat a selection while its response is pending. + * @returns this attempt's Host refusal, or undefined when successful or no switch starts. */ async apply(): Promise { - let pending = this.pendingSelection - while (pending !== undefined) { - await pending - const error = this.store.getSnapshot().error - if (error !== null) return error - pending = this.pendingSelection - if (pending === undefined && this.staged.id === undefined) return - } + if (this.store.getSnapshot().busy) return const staged = this.staged.id const session = this.currentSession() if (staged === undefined) { diff --git a/packages/client/ui-agent-preset/tests/apply.client.spec.ts b/packages/client/ui-agent-preset/tests/apply.client.spec.ts index 378b40006f..1e28cb44f4 100644 --- a/packages/client/ui-agent-preset/tests/apply.client.spec.ts +++ b/packages/client/ui-agent-preset/tests/apply.client.spec.ts @@ -6,7 +6,7 @@ */ import { Context } from '@deepseek-ai/cordis' -import { describe, expect, it, onTestFinished, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' @@ -76,7 +76,6 @@ async function bench(options: { failSettingsUpdate?: boolean selectGate?: Promise settingsRosterGate?: Promise - refuseSelect?: boolean } = {}) { const ctx = new Context() // The host's answer, mutable so a spec can move the default the way the @@ -154,9 +153,7 @@ async function bench(options: { deletePreset: () => Promise.resolve({ ok: true as const, value: undefined }), select: (_agentId: SessionId, agentPreset: string) => { calls.push(`select:${agentPreset}`) - return Promise.resolve(options.selectGate).then(() => options.refuseSelect === true - ? { ok: false as const, error: new RemoteError('gateway/internal', 'preset refused', {}) } - : { ok: true as const, value: agentPreset }) + return Promise.resolve(options.selectGate).then(() => ({ ok: true as const, value: agentPreset })) }, } ctx.provide('remote.agentPresets', agentPresets as never) @@ -718,10 +715,8 @@ describe('ui-agent-preset apply', () => { conversation() }) - it.each([false, true])('awaits the staged choice before first send and propagates refusal (%s)', async (refuseSelect) => { - const selection = Promise.withResolvers() - const { ctx, slots, calls } = await bench({ refuseSelect, selectGate: selection.promise }) - onTestFinished(async () => { selection.resolve(undefined); await ctx.fiber.dispose() }) + it('applies the staged choice to the blank session the flow lands on', async () => { + const { ctx, slots, calls } = await bench() declareRoot(slots) declareConversation(slots) ctx.provide('conversation', {} as never) @@ -741,8 +736,6 @@ describe('ui-agent-preset apply', () => { .inject as unknown as (sessionId?: SessionId) => AgentPresetSeatInjected const chip = injectSeat() - await ctx.serial('conversation/prepare-first-send', SessionId('absent')) - await chip.load() // Picked on the hero screen, where there is no session yet. await chip.select('minimal') @@ -754,16 +747,10 @@ describe('ui-agent-preset apply', () => { } sessions.notify() const bound = injectSeat(SessionId('s1')) - const preparing = ctx.serial('conversation/prepare-first-send', SessionId('s1')) - const settled = refuseSelect ? expect(preparing).rejects.toThrow('preset refused') : expect(preparing).resolves.toBeUndefined() - selection.resolve(undefined) - await settled - await ctx.serial('conversation/prepare-first-send', SessionId('s1')) await bound.load() // Connecting a workspace produced the session; the stage reaches it there. await vi.waitFor(() => { expect(calls).toContain('select:minimal') }) - expect(calls.filter(call => call === 'select:minimal')).toHaveLength(1) }) it('applies the stage to a session that records no preset of its own', async () => { @@ -959,28 +946,6 @@ describe('ui-agent-preset apply', () => { }) describe('AgentPresetSeatController reconciliation', () => { - it.each([false, true])('shares the result of an active preset selection (refused: %s)', async (refused) => { - const refusal = { ok: false as const, error: new RemoteError('gateway/internal', 'selection refused', {}) } - const reply = Promise.withResolvers<{ ok: true; value: string } | typeof refusal>() - const select = vi.fn(() => reply.promise) - const controller = new AgentPresetSeatController({ remote: { agentPresets: { select } } } as never, - () => ({ id: SessionId('blank'), blank: true, projectionValues: { agentPreset: 'standard' } })) - const selecting = controller.select('minimal') - let prepared = false - const preparation = controller.apply().finally(() => { prepared = true }) - try { - expect(prepared).toBe(false) - expect(select).toHaveBeenCalledOnce() - reply.resolve(refused ? refusal : { ok: true, value: 'minimal' }) - await expect(preparation).resolves.toBe(refused ? 'selection refused' : undefined) - await selecting - expect(select).toHaveBeenCalledOnce() - } finally { - reply.resolve({ ok: true, value: 'minimal' }) - await Promise.allSettled([selecting, preparation]) - } - }) - it.each([ { refuseFirst: false, refuseLatest: false }, { refuseFirst: false, refuseLatest: true }, @@ -1001,17 +966,16 @@ describe('AgentPresetSeatController reconciliation', () => { const first = controller.select('minimal') let settingsSettled = false const settings = controller.syncBlankSession(session.id, 'cordis').finally(() => { settingsSettled = true }) - const repeatedFirst = controller.apply() + await controller.apply() expect(requests.map(request => request.preset)).toEqual(['minimal']) requests[0]!.outcome.resolve(refuseFirst ? refusal : { ok: true, value: 'minimal' }) await first expect(requests.map(request => request.preset)).toEqual(['minimal', 'cordis']) expect(settingsSettled).toBe(false) - const repeatedLatest = controller.apply() + await controller.apply() expect(requests).toHaveLength(2) requests[1]!.outcome.resolve(refuseLatest ? refusal : { ok: true, value: 'cordis' }) await expect(settings).resolves.toBe(refuseLatest ? 'selection refused' : undefined) - await Promise.all([repeatedFirst, repeatedLatest]) expect(controller.store.getSnapshot()).toMatchObject({ current: refuseLatest ? 'standard' : 'cordis', busy: false, error: refuseLatest ? 'selection refused' : null, @@ -1028,10 +992,10 @@ describe('AgentPresetSeatController reconciliation', () => { () => ({ id: SessionId('blank'), blank: true, projectionValues: { agentPreset: 'standard' } })) const first = controller.select('minimal') controller.stage('cordis', true) - const repeated = controller.apply() + await controller.apply() expect(select).toHaveBeenCalledOnce() firstReply.resolve(refused ? refusal : { ok: true, value: 'minimal' }) - await Promise.all([first, repeated]) + await first expect(controller.store.getSnapshot().current).toBe('cordis') await controller.apply() expect(select.mock.calls.map(call => call[1])).toEqual(['minimal', 'cordis']) diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 2bcda4be9c..b871029e8d 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md -README.md: f921aa4a9aa7e9cea0a8a2c2c875b3f1d7c27bd8 -README.zh.md: b432995b1e42292a65558f37f153920cc7ecbbf2 +README.md: 16e821ed4caabae491d552a823bd69a2e976e2bd +README.zh.md: 7316b00c69ca74284b81678082d93e870dee6bbe diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index f921aa4a9a..16e821ed4c 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -50,10 +50,6 @@ Claimed commands retain their identity and highlight when only their arguments a Workspace selection uses `uiWorkspace.openWorkspace` to prepare the target and commit navigation. Draft text and attachments move in its synchronous preparation callback only while that request is current; later navigation or owner disposal leaves the original draft intact. -The Client chooses the default directory name and initial title when sending: Chinese uses `默认工作区`, English uses `Default workspace`, and other languages use directory `default-workspace` with title `Default workspace`. The request retains those names during initialization. A retry after failed initialization uses the current language; a successfully initialized Workspace keeps its directory and title across language changes. - -On first use, the same input accepts text before a Workspace is selected. The first send prepares the [default Workspace](../../workspace/workspace/README.md#first-use-workspace), selects its blank Session, transfers the draft, and uses ordinary message submission. Preparation locks further input. Failure preserves the draft and offers Cancel or Choose folder through the existing picker. A manually chosen folder receives the unsent draft; the user sends again. Once created, the Workspace survives a prompt failure. `conversation/prepare-first-send` awaits staged Session settings before automatically submitting the transferred first-use draft; a rejected listener keeps that draft and reports its error. If navigation releases the destination Session while preparation is pending, automatic submission stops and its persisted draft remains available on reopening. - The package occupies the root-scoped `main` key `conversation`. Its `main.conversation` shell keeps the resident `conversation.header` outside the optional-Session `conversation.content` Component Factory. The header hosts root-scoped navigation without a selected Session; titles, actions, and View tabs remain in its strict Session child. The Factory owns the shared body and Composer, reads the current Session through its standard Hook, and exposes strict-Session `views` plus root-scoped `widthControls` local positions. Its default adapter renders the existing `conversation.session` entry, while the main occurrence selects the width handles; an embedded occurrence can replace `views` and omit those handles without rendering the main Header. The shared body and Composer register the queue and Todo docks. The Todo dock uses the shared panel elevation above the composer; its rows use the shared idle, ongoing, and done markers for pending, in-progress, and completed items. `ctx.uiSession.provide()` materializes the Conversation and input sources from the same Session binding and supplies `inputActions` as a stable standard prop. A blank Session retains the header's leading and corner controls, including the right-sidebar opener, while hiding its title, actions, utilities, and View tabs. Selecting a Workspace creates the Session needed by these controls; the first message is not required. Without a selected Session, the strict header is absent; the resident container reserves a 40px drag band on macOS desktop and no empty vertical space on Web, Windows, or Linux. Sidebar entries retain their own data and execution prerequisites. A started Session header uses one row when fewer than two Views are available; the tab row reserves space only while rendered. @@ -64,7 +60,7 @@ The shell reads the persisted View preference before rendering when a Session fi Active transcripts in the main occurrence expose content-width drag handles in their uncovered side gutters; embedded occurrences omit them. A View that paints into a gutter raises only its concrete painted element above the handle; transparent full-width wrappers stay below so they do not claim empty gutter. This requires the path between that element and the Conversation body to remain outside an intermediate stacking context; the shipped Chromium behavior is pinned by the browser scenario. Chat applies the rule to table elements, while its column-bounded tool cards need no raise. Wheel motion over a handle still scrolls the transcript, while Ctrl+wheel remains a browser zoom gesture. The sticky composer intentionally owns its full footer band, which is not a resize target; an already-captured drag lifts its indicator until release ([handle styles](src/client/skeleton/ConversationRoot.module.css)). -The resident composer survives no-Session and Session transitions. Whitespace hides its placeholder; a whitespace-only draft without attachments cannot be sent. Before a Session exists, the composer holds a local text draft; sending waits for complete Workspace and Session baselines and then prepares the default Workspace. The surface is a shell-owned Lexical editor: reference chips are atomic decorator nodes carrying the owner's serialization identity (submission expands them through the owner codec), claimed slash commands stay styled leading text, folder text references carry the folder glyph as an icon prefix, and the draft's clipboard projection is mirrored into the per-Session Conversation store. QueueDock reads `next-turn` directly from the Session `inbox` projection, including cold recovered messages. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews render sent text through the shared inline reference projection from `ui-primitives` (wire session forms fold to their label) and show local or durable images and files in original attachment order. Images use thumbnails; files use compact name-and-size cards. An edit exposes the literal sent text, and durable thumbnails resolve through the session image URL cache. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace. The composer keymap arbitrates the trigger menu's keys through the slash pipeline — Tab settles the highlighted completion (or drills a drillable one), Escape and Shift+Tab leave the menu without settling — and leaves every other key to the editor. An overlay that takes the keyboard hands it back through `SessionInput.focus()`, which rides Lexical's own focus so the caret returns where the draft left it rather than at the start. +The resident composer survives no-Session and Session transitions. Whitespace hides its placeholder; a whitespace-only draft without attachments cannot be sent. The no-Session state keeps the same composer surface mounted but inert while the Workspace picker connects a blank Session. The surface is a shell-owned Lexical editor: reference chips are atomic decorator nodes carrying the owner's serialization identity (submission expands them through the owner codec), claimed slash commands stay styled leading text, folder text references carry the folder glyph as an icon prefix, and the draft's clipboard projection is mirrored into the per-Session Conversation store. QueueDock reads `next-turn` directly from the Session `inbox` projection, including cold recovered messages. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews render sent text through the shared inline reference projection from `ui-primitives` (wire session forms fold to their label) and show local or durable images and files in original attachment order. Images use thumbnails; files use compact name-and-size cards. An edit exposes the literal sent text, and durable thumbnails resolve through the session image URL cache. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace. The composer keymap arbitrates the trigger menu's keys through the slash pipeline — Tab settles the highlighted completion (or drills a drillable one), Escape and Shift+Tab leave the menu without settling — and leaves every other key to the editor. An overlay that takes the keyboard hands it back through `SessionInput.focus()`, which rides Lexical's own focus so the caret returns where the draft left it rather than at the start. Default sends commit optimistically: Enter clears the draft, occurrence table, and undo history in the same transaction, keeps the composer in `plain`, and runs the send as a detached attempt, so typing and further sends continue during the flight. `sendSession` registers a Session submission echo (`session.beginSubmission`) with the delivery mode before serializing, preserving selected image and file order in `pendingSubmissions`; Session derives the placement from that mode and its current running state, so idle sends use the transcript, busy Queue sends use QueueDock, and busy Steer sends use the pending-steering surface. It then yields one paint, encodes images through the browser's native `FileReader` data-URL path, and cites staged file receipts. Command submissions use the same receipts for generic files, so sending `/goal` or `/plan` never reads those browser files again. The prompt reuses the submission `requestId`; queue and history observation by that `rpcId` retires the echo once. Concurrent failures are restored together in submission order until the user edits the restored content; command submissions keep the frozen `submitting` phase. Detached attempts retain their attachment ids through admission and Session scope disposal. An observed retirement immediately exposes each image preview through the durable cache, replaces it with the canonical URL after fetching the admitted attachment, revokes each URL after its use ends, and releases file cards. Selected generic files enter one FIFO background-upload queue; `maxConcurrentFileUploads` defaults to two active Worker transports, the Conversation service retains queued and active operations plus byte progress across Session navigation, and removing a draft skips its queued transfer or aborts its active transport. Continuable subagents disable attachment intake and skip local echoes because their transport does not preserve the browser request id. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index b432995b1e..7316b00c69 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -50,10 +50,6 @@ target package 通过 declaration merge 扩展 snapshot 与 Location data map, 工作区选择使用 `uiWorkspace.openWorkspace` 准备目标并提交导航。草稿文字和附件仅在该请求仍为当前请求时,通过它的同步准备回调搬移;后续导航或所有者释放会保留原草稿。 -Client 在发送时决定默认目录名和初始标题:中文使用 `默认工作区`,英文使用 `Default workspace`,其他语言使用目录 `default-workspace` 和标题 `Default workspace`。初始化期间,请求保留这些名称。初始化失败后的重试使用当前语言;初始化成功的 Workspace 在切换语言后仍保留原目录和标题。 - -首次使用时,同一个输入框允许在选择 Workspace 前输入文字。首条消息会准备[默认工作区](../../workspace/workspace/README.zh.md#first-use-workspace)、选中其 blank Session、转移草稿,再使用普通消息提交流程。准备期间锁定后续输入。失败时保留草稿,并提供“取消”或通过已有选择器“选择文件夹”。手动选择的文件夹接收未发送草稿,用户再次发送。Workspace 创建成功后,不会因提示词发送失败而消失。`conversation/prepare-first-send` 在自动提交已转移的首次使用草稿前等待暂存的 Session 设置完成;监听器拒绝时保留该草稿并显示错误。如果导航在准备期间释放了目标 Session,自动提交会停止,已持久化的草稿会在重新打开时保留。 - 本包占据 root 作用域 `main` 中的 `conversation` key。其 `main.conversation` 外壳将常驻的 `conversation.header` 放在可选 Session 的 `conversation.content` Component Factory 外。未选中 Session 时,头部仍承载根作用域导航;标题、操作和 View 标签保留在严格 Session 子组件中。Factory 拥有共享正文与 Composer,通过其标准 Hook 读取当前 Session,并公开 strict-Session `views` 与 root-scoped `widthControls` 两个局部位置。默认 adapter 渲染现有 `conversation.session` entry,主 occurrence 选择宽度拖拽条;嵌入式 occurrence 可以替换 `views`、省略拖拽条,且不渲染主 Header。共享正文与 Composer 注册 queue dock 和 Todo dock。Todo dock 在 composer 上方使用共享面板 elevation;其中的行分别以共享 idle、ongoing 与 done 标记表示待处理、进行中与已完成。`ctx.uiSession.provide()` 从同一个 Session binding 物化 Conversation 与 input source,并将 `inputActions` 作为稳定标准 prop 提供。 blank Session 保留 header 的 leading 与 corner 控件,包括右侧栏展开入口,同时隐藏标题、actions、utilities 和 View tabs。选择 Workspace 会创建这些控件所需的 Session,无需先发送消息。没有选中 Session 时,strict header 不挂载;常驻容器在 macOS 桌面保留 40px 拖拽区域,在 Web、Windows 或 Linux 上不预留空白高度。侧栏各入口仍遵循自身的数据与执行环境要求。 已开始的 Session 在可用 View 少于两个时使用单行标题栏,仅在渲染标签行时保留其高度。 @@ -64,7 +60,7 @@ Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染 主 occurrence 的活跃 transcript 只在未被内容覆盖的两侧沟槽中提供正文宽度拖拽条;嵌入式 occurrence 省略这些拖拽条。View 如果绘制进沟槽,只将具体的可见元素提到拖拽条上方;透明的全宽包装层保持在下方,不会占用空白沟槽。该规则要求此元素与 Conversation body 之间不能引入中间堆叠上下文;浏览器场景固定了交付 Chromium 的行为。Chat 将该规则用于表格元素,其限定在阅读列内的工具卡片无需提高层级。指针位于拖拽条上时,滚轮仍会滚动 transcript,Ctrl+滚轮则保留为浏览器缩放手势。粘滞 composer 刻意拥有完整的底部区带,该区域不是宽度调整目标;已捕获的拖拽会将指示线提高到松开为止([拖动手柄样式](src/client/skeleton/ConversationRoot.module.css))。 -常驻 composer 在无 Session 与有 Session 之间保持挂载。输入空白字符会隐藏占位提示;没有附件的纯空白草稿无法发送。Session 尚未存在时,composer 保存本地文字草稿;发送会等待 Workspace 与 Session 基线完整加载,然后准备默认工作区。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 保持为带样式的行首文本,文件夹文本引用以图标前缀携带文件夹图形,草稿的剪贴板投影镜像到逐 Session Conversation store。QueueDock 直接从 Session 的 `inbox` 投影读取 `next-turn`,包含从冷状态恢复的消息。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览经 `ui-primitives` 的共享行内引用投影渲染已发送文本(wire 会话形式折叠为其标签),并按原始附件顺序展示本地或持久化的图片和文件。图片使用缩略图,文件使用紧凑的名称与大小卡片。编辑态展示字面发送文本,持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。 composer 键盘映射经斜杠流水线裁决触发菜单的按键——Tab 确认高亮补全项(可下钻项则下钻),Escape 与 Shift+Tab 离开菜单且不选定——其余按键交给编辑器自身。 接管键盘的浮层通过 `SessionInput.focus()` 把键盘还回来,该路径走 Lexical 自己的 focus,因此光标回到草稿原来的位置而不是开头。 +常驻 composer 在无 Session 与有 Session 之间保持挂载。输入空白字符会隐藏占位提示;没有附件的纯空白草稿无法发送。无 Session 时,同一个编辑器表面保持 inert,Workspace picker 连接 blank Session。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 保持为带样式的行首文本,文件夹文本引用以图标前缀携带文件夹图形,草稿的剪贴板投影镜像到逐 Session Conversation store。QueueDock 直接从 Session 的 `inbox` 投影读取 `next-turn`,包含从冷状态恢复的消息。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览经 `ui-primitives` 的共享行内引用投影渲染已发送文本(wire 会话形式折叠为其标签),并按原始附件顺序展示本地或持久化的图片和文件。图片使用缩略图,文件使用紧凑的名称与大小卡片。编辑态展示字面发送文本,持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。 composer 键盘映射经斜杠流水线裁决触发菜单的按键——Tab 确认高亮补全项(可下钻项则下钻),Escape 与 Shift+Tab 离开菜单且不选定——其余按键交给编辑器自身。 接管键盘的浮层通过 `SessionInput.focus()` 把键盘还回来,该路径走 Lexical 自己的 focus,因此光标回到草稿原来的位置而不是开头。 默认发送采用乐观提交:Enter 在同一事务里清空草稿、occurrence 表和撤销历史,composer 保持 `plain`,发送作为 detached attempt 运行,发送期间可以继续输入和提交。`sendSession` 在序列化之前用投递模式注册 Session 提交回显(`session.beginSubmission`),并在 `pendingSubmissions` 中保留图片与文件的选择顺序;Session 根据该模式与当前运行状态推导位置,因此空闲发送进入 transcript(文本记录),繁忙时 Queue 进入 QueueDock,繁忙时 Steer 进入 pending-steering 区域。随后让出一帧,图片经浏览器原生 `FileReader` data-URL 路径编码,文件则引用已暂存凭证。命令提交也用同一凭证表示通用文件,因此发送 `/goal` 或 `/plan` 时不会再次读取这些浏览器文件。提示词复用提交 `requestId`;queue 或历史以同一 `rpcId` 被观察后,回显只退休一次。多个并发发送失败时,在用户编辑还原内容之前按提交顺序合并还原;命令提交保持冻结的 `submitting` 阶段。Detached attempt 持有附件 id,直到 admission 完成或 Session scope 销毁。回显以 observed 退休时,durable 图片缓存立即公开每个预览 URL,读取 admitted 附件后用规范化 URL 替换预览,并在各 URL 停止使用后撤销,同时释放文件卡。选中的通用文件进入同一个先进先出的后台上传队列;`maxConcurrentFileUploads` 默认允许两个 Worker transport 同时运行,Conversation 服务在切换 Session 时继续持有排队和运行中的传输操作及字节进度,移除草稿会跳过排队中的传输或中止正在运行的传输。continuable 子代理禁用附件入口,也不创建本地回显,因为其 transport 不保留浏览器 request id。 diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index a02e0737f0..07d754d873 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -2,7 +2,6 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type { ISessions, SessionBinding } from '@deepseek-ai/dsh-api-session-controller/client' -import type { WorkspaceInitializeDefaultRequest } from '@deepseek-ai/dsh-api-workspace-controller/client' import { IconPaperclipOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import { createSnapshotStore, type BoundActions } from '@deepseek-ai/dsh-client-store' import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' @@ -18,13 +17,13 @@ import type { ComposerBarInjected, ConversationInjected, ConversationSessionHeaderInjected, ConversationSessionInjected, DraftFileUploads, } from './contract/slots.ts' +import type { InputNotice } from './contract/input.ts' import { createConversationStore, readConversationViewPreference } from './stores.ts' import { ConversationController, UnsupportedImageMediaTypeError } from './service.ts' import type { IConversation } from './service.ts' import { ComposerBlockRegistry } from './input/blocks.ts' import type { ComposerBlock } from './contract/composer-blocks.ts' import { InputHub } from './input/hub.ts' -import { FirstDraft } from './input/first-draft.ts' import { ComposerSubmissionPolicy } from './input/submission-policy.ts' import { queueDockEntry } from './queue/QueueDock.tsx' import { EnterBehaviorRow } from './settings/EnterBehaviorRow.tsx' @@ -65,10 +64,19 @@ export const Config: z = z.object({ // Stable no-session sources keep the renderer's observable-hook cache and // hook order unchanged across current-Session transitions. +const ABSENT_NOTICES = { + getSnapshot: (): InputNotice | null => null, + subscribe: () => () => {}, +} const ABSENT_BLOCK = { getSnapshot: (): ComposerBlock | undefined => undefined, subscribe: () => () => {}, } +const EMPTY_LEXICON: ReadonlyMap<'/' | '@', readonly string[]> = new Map() +const ABSENT_LEXICON = { + getSnapshot: () => EMPTY_LEXICON, + subscribe: () => () => {}, +} const ABSENT_MENU_LAUNCHER = { getSnapshot: (): string | null => null, subscribe: () => () => {}, @@ -79,19 +87,12 @@ const ABSENT_FILE_UPLOADS = { subscribe: () => () => {}, } -// ui-workspace consumes Conversation slots, so this reverse runtime dependency -// uses a local method projection to keep the TypeScript project graph acyclic. interface WorkspaceNavigation { openSession(sessionId: SessionId): void openWorkspace( workspaceId: Parameters[0], beforeOpen: (sessionId: SessionId) => void, ): Promise - openDefaultWorkspace( - request: WorkspaceInitializeDefaultRequest, - beforeOpen: (sessionId: SessionId) => void, - signal: AbortSignal, - ): Promise } /** Action registration used by the composer without importing its command-UI consumer. */ @@ -205,19 +206,6 @@ export function apply(ctx: Context, config: Config = Config({})): void { }, 'ui-conversation: View selection') const inputHub = new InputHub(ctx, t) - const firstDraft = new FirstDraft(ctx, { - open: (beforeOpen, signal) => { - const language = ctx.locale.getSnapshot().active.toLowerCase().split('-')[0] - // Persisted Workspace names follow the send-time language, including the English fallback. - const title = (language === 'zh' ? zh : en)['defaultWorkspace.title'] - return workspaceNavigation.openDefaultWorkspace({ - directoryName: language === 'zh' || language === 'en' ? title : 'default-workspace', - title, - }, beforeOpen, signal) - }, - shell: id => inputHub.shell(id), - isCurrent: (id, shell) => sessions.binding(id) !== undefined && inputHub.shell(id) === shell, - }) const composerBlocks = new ComposerBlockRegistry() ctx.inject(['commandUi'], (scope) => { @@ -278,11 +266,8 @@ export function apply(ctx: Context, config: Config = Config({})): void { inject: (sessionId: SessionId | undefined): ConversationInjected => ({ hooks: { composerBlock: sessionId === undefined ? ABSENT_BLOCK : composerBlocks.storeFor(sessionId), - firstDraft: firstDraft.state, }, - dismissDefaultFailure: () => { firstDraft.dismiss() }, selectWorkspace: workspaceId => workspaceNavigation.openWorkspace(workspaceId, (nextId) => { - if (sessionId === undefined) firstDraft.transfer(nextId) if (sessionId !== undefined && nextId !== sessionId) { const from = inputHub.shell(sessionId) const draft = from.snapshot.draft @@ -388,7 +373,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { inject: (sessionId: SessionId | undefined): ComposerBarInjected => { if (sessionId === undefined) { return { - keyboard: firstDraft.shell, + keyboard: undefined, addFiles: undefined, removeAttachment: undefined, resolveDraftAttachments: undefined, @@ -396,11 +381,10 @@ export function apply(ctx: Context, config: Config = Config({})): void { toggleCommandMenu: undefined, stop: undefined, hooks: { - composerInput: firstDraft.shell.state, busyEnter: submissionPolicy.busyEnter, fileUploads: ABSENT_FILE_UPLOADS, - notices: firstDraft.shell.notices, - lexicon: firstDraft.shell.lexicon, + notices: ABSENT_NOTICES, + lexicon: ABSENT_LEXICON, menuLauncher: ABSENT_MENU_LAUNCHER, }, } @@ -449,7 +433,6 @@ export function apply(ctx: Context, config: Config = Config({})): void { }) }, hooks: { - composerInput: shell.state, busyEnter: submissionPolicy.busyEnter, fileUploads: conversation.fileUploads, notices: shell.notices, diff --git a/packages/client/ui-conversation/src/client/contract/input.ts b/packages/client/ui-conversation/src/client/contract/input.ts index be338eb3df..b4cd6b9bdf 100644 --- a/packages/client/ui-conversation/src/client/contract/input.ts +++ b/packages/client/ui-conversation/src/client/contract/input.ts @@ -34,12 +34,6 @@ export interface SubmitOutcome { readonly text?: string } -/** State of first-use Workspace preparation. */ -export interface FirstDraftState { - readonly busy: boolean - readonly failed: boolean -} - /** Command-mode credential supplied by one input-trigger source. */ export interface CommandClaim { /** Catalog command name without the leading slash (the key of per-command composer copy such as `hint.*`). */ diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index a0d9a6d592..023babf26e 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -16,7 +16,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types' import type { ComposerBlock } from './composer-blocks.ts' -import type { DraftAttachmentId, FirstDraftState, InputActions, InputNotice, InputState } from './input.ts' +import type { DraftAttachmentId, InputActions, InputNotice, InputState } from './input.ts' import type { ComposerKeyboard, EditSelection } from './draft-editor.ts' import type { createConversationStore } from '../stores.ts' import type { BusyEnterBehavior } from './composer-submission.ts' @@ -319,13 +319,8 @@ export type ConvViewProps = PropsRuntime<'conversation.view'> export interface ConversationInjected { /** Connect and open a blank Session in the selected Workspace. */ selectWorkspace: (workspaceId: WorkspaceId) => Promise - /** Dismiss default Workspace creation failure without discarding input. */ - dismissDefaultFailure: () => void /** Session-addressed composer block source, or the stable absent source. */ - hooks: { - composerBlock: ObservableSnapshot - firstDraft: ObservableSnapshot - } + hooks: { composerBlock: ObservableSnapshot } } /** Business callbacks injected into the strict Session body. */ @@ -370,7 +365,7 @@ export interface ComposerBarOwnerProps { /** Package-private operations injected into the resident composer bar. */ export interface ComposerBarInjected { - keyboard: ComposerKeyboard + keyboard: ComposerKeyboard | undefined addFiles: ((files: readonly File[]) => string | null) | undefined removeAttachment: ((id: DraftAttachmentId) => void) | undefined resolveDraftAttachments: ((ids: readonly DraftAttachmentId[]) => readonly ComposerAttachment[]) | undefined @@ -379,8 +374,6 @@ export interface ComposerBarInjected { toggleCommandMenu: ((selection: EditSelection) => void) | undefined stop: (() => void) | undefined hooks: { - /** Resident editor state, including input before a Session exists. */ - composerInput: ObservableSnapshot /** * Live busy-state submission preference: the delivery mode plain Enter * and the primary Send button use while the addressed agent is busy. diff --git a/packages/client/ui-conversation/src/client/index.ts b/packages/client/ui-conversation/src/client/index.ts index 468fc9c198..73ddc6d7d3 100644 --- a/packages/client/ui-conversation/src/client/index.ts +++ b/packages/client/ui-conversation/src/client/index.ts @@ -72,14 +72,6 @@ export type { ArbitrateKey, ArbitrateOutcome, ReferenceInsert, TokenSpan } from export type { ComposerBlock, ComposerBlocks } from './contract/composer-blocks.ts' declare module '@deepseek-ai/cordis' { - interface Events { - /** - * Finish staged settings before automatically submitting the first-use draft to its new Session. - * @mode serial - * @param sessionId - destination Session. - */ - 'conversation/prepare-first-send'(sessionId: import('@deepseek-ai/dsh-session/types').SessionId): void | Promise - } interface Context { /** Scope-addressed Conversation actions and per-Session input registry. */ conversation: import('./service.ts').IConversation diff --git a/packages/client/ui-conversation/src/client/input/facade.ts b/packages/client/ui-conversation/src/client/input/facade.ts index 77bff28708..4f4d0aa300 100644 --- a/packages/client/ui-conversation/src/client/input/facade.ts +++ b/packages/client/ui-conversation/src/client/input/facade.ts @@ -5,8 +5,8 @@ * scoped-event application verbs, the submit transaction plumbing * (adjudicate via the session's InputTriggerController; claim.submit; default * sink), the notice channel, and the draft persistence mirror. - * Package-private; InputHub binds Session events, while FirstDraft owns the - * local editor used before a Session exists. + * Package-private; the hub alone constructs it and wires the scoped event + * listeners onto it. */ import type { Context } from '@deepseek-ai/cordis' import type { InboxState } from '@deepseek-ai/dsh-agent/types' diff --git a/packages/client/ui-conversation/src/client/input/first-draft.ts b/packages/client/ui-conversation/src/client/input/first-draft.ts deleted file mode 100644 index 8dc7fb32a6..0000000000 --- a/packages/client/ui-conversation/src/client/input/first-draft.ts +++ /dev/null @@ -1,82 +0,0 @@ -/** Local text draft retained until the first Workspace and Session can accept it. */ -import type { Context } from '@deepseek-ai/cordis' -import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' -import type { SessionId } from '@deepseek-ai/dsh-session/types' -import type { FirstDraftState, SubmitOutcome } from '../contract/input.ts' -import type { InputSubmitMode } from '../contract/composer-submission.ts' -import { SessionInputShell } from './facade.ts' - -/** First-use navigation and the resident destination input. */ -interface FirstDraftDeps { - open(beforeOpen: (id: SessionId) => void, signal: AbortSignal): Promise - shell(id: SessionId): SessionInputShell - /** Whether the borrowed input still belongs to the retained Session generation. */ - isCurrent(id: SessionId, shell: SessionInputShell): boolean -} - -/** Owns a root-lifetime text editor without allocating a Host Session. */ -export class FirstDraft { - /** Preparation progress and the recoverable directory failure. */ - readonly state = createSnapshotStore({ busy: false, failed: false }) - /** Local editor owns failed-submit restoration before transfer to a Host Session. */ - readonly shell: SessionInputShell - private pending: { text: string; transferred: boolean } | undefined - - /** @param ctx - Client plugin lifetime. @param deps - Workspace navigation and Session input access. */ - constructor(private readonly ctx: Context, private readonly deps: FirstDraftDeps) { - this.shell = new SessionInputShell({ - actx: ctx, - defaultSink: (text, _attachments, mode, signal) => this.send(text, mode, signal), - commandAttachments: { - serialize: () => Promise.resolve([]), - release: () => {}, - unsupportedNotice: () => '', - }, - }) - ctx.effect(() => () => { this.shell.dispose() }, 'conversation.input: first-use draft') - } - - /** Dismiss the preparation failure while retaining the draft. */ - dismiss(): void { - this.state.set({ ...this.state.getSnapshot(), failed: false }) - } - - /** - * Move the unsent text to a selected Session. - * @param id - retained destination Session receiving the unsent text. - */ - transfer(id: SessionId): void { - const text = this.pending?.text ?? this.shell.snapshot.draft - if (text !== '') this.deps.shell(id).setDraft(text) - if (this.pending !== undefined) this.pending.transferred = true - this.shell.setDraft('') - this.dismiss() - } - - private async send(text: string, mode: InputSubmitMode, signal: AbortSignal): Promise { - if (this.pending !== undefined) return { kind: 'error' } - const pending = { text, transferred: false } - this.pending = pending - this.state.set({ busy: true, failed: false }) - let target: SessionInputShell | undefined - try { - const id = await this.deps.open((nextId) => { this.transfer(nextId) }, signal) - if (id === undefined) return { kind: pending.transferred ? 'success' : 'error' } - target = this.deps.shell(id) - await this.ctx.serial('conversation/prepare-first-send', id) - signal.throwIfAborted() - if (!this.deps.isCurrent(id, target)) return { kind: 'success' } - target.submit(mode) - return { kind: 'success' } - } catch (error) { - if (!signal.aborted) { - if (target !== undefined) target.notify('error', error instanceof Error ? error.message : String(error)) - else if (!pending.transferred) this.state.set({ busy: true, failed: true }) - } - return { kind: pending.transferred ? 'success' : 'error' } - } finally { - this.pending = undefined - this.state.set({ ...this.state.getSnapshot(), busy: false }) - } - } -} diff --git a/packages/client/ui-conversation/src/client/locales.ts b/packages/client/ui-conversation/src/client/locales.ts index ecf2141f1d..464ff55e17 100644 --- a/packages/client/ui-conversation/src/client/locales.ts +++ b/packages/client/ui-conversation/src/client/locales.ts @@ -9,10 +9,6 @@ const PLAN_NEXT_ACTION_EN = 'describe your task to generate plan' /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { - 'defaultWorkspace.failed': '无法创建默认工作区', - 'defaultWorkspace.title': '默认工作区', - 'defaultWorkspace.retry': '请选择一个文件夹后重试', - 'defaultWorkspace.choose': '选择文件夹', 'hint.plan': PLAN_NEXT_ACTION_ZH, 'hint.goal': '输入目标,智能体将持续执行', 'hint.goal.active': '当前目标进行中。可输入 edit 修改 / pause 暂停 / resume 继续 / clear 清除', @@ -22,7 +18,6 @@ export const zh = { 'placeholder.parentOffline': '父会话已离线,无法继续发送;仍可停止当前运行', 'placeholder.hero': '描述你想要构建的内容, / 调用指令, @ 文件或对话', 'placeholder.workspace': '选择一个工作区开始', - 'placeholder.preparing': '正在准备工作区…', 'placeholder.steerQueue': 'Cmd/Ctrl+Enter 插话发送全部排队消息', 'input.commands': '添加文件或调用指令', 'input.file': '文件', @@ -365,10 +360,6 @@ export type ConversationKey = keyof typeof zh /** English dictionary, checked complete against the zh key set. */ export const en = { - 'defaultWorkspace.failed': 'Unable to create default workspace', - 'defaultWorkspace.title': 'Default workspace', - 'defaultWorkspace.retry': 'Please choose a folder and try again', - 'defaultWorkspace.choose': 'Choose folder', 'hint.plan': PLAN_NEXT_ACTION_EN, 'hint.goal': 'describe the objective for a long-running task', 'hint.goal.active': 'goal active — edit / pause / resume / clear', @@ -378,7 +369,6 @@ export const en = { 'placeholder.parentOffline': 'Parent session offline; sending is unavailable but you can still stop the run', 'placeholder.hero': 'Describe what you want to build, / commands, @ files or sessions', 'placeholder.workspace': 'Choose a workspace to start', - 'placeholder.preparing': 'Preparing workspace…', 'placeholder.steerQueue': 'Cmd/Ctrl+Enter steers all queued messages', 'input.commands': 'Add files or run commands', 'input.file': 'File', diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx index 82ea0e533d..adace1c113 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx @@ -1,6 +1,5 @@ import { useCallback, useEffect, useRef, useState } from 'react' import clsx from 'clsx' -import { Button, Modal } from '@deepseek-ai/dsh-client-ui-primitives' import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types' import type { ConversationContentProps, ConversationViewsProps, InputZone } from '../contract/slots.ts' import { HeroShell, WorkspaceChip, workspaceLabel } from './EmptyHero.tsx' @@ -23,7 +22,7 @@ export function ConversationContent(props: ConversationContentProps) { const { sessionId, phase, hero, useSession, useSessions, useSessionStatus, useWorkspaces, useInput, useComposerBlock, renderSlot, renderSlotChain, - selectWorkspace, dismissDefaultFailure, useFirstDraft, t, useFactorySlot, + selectWorkspace, t, useFactorySlot, } = props const session = useSession(snapshot => snapshot) const Views = useFactorySlot('views', ConversationSessionView) @@ -34,8 +33,6 @@ export function ConversationContent(props: ConversationContentProps) { const inputState = useInput(s => s) const cwd = useSessions(s => sessionId === undefined ? undefined : s.byId[sessionId]?.cwd) const workspaces = useWorkspaces(s => s) - const sessionsReady = useSessions(s => s.phase === 'ready') - const firstDraft = useFirstDraft(s => s) // A plugin this package cannot import (ui-model-selection) says this session cannot // send; its reason is already localized by whoever raised it. const composerBlock = useComposerBlock(block => block) @@ -130,22 +127,24 @@ export function ConversationContent(props: ConversationContentProps) {
) - // First-use sending waits for both baselines. A blank Session whose - // Workspace disappeared still requires explicit directory selection. - const needsWorkspace = sessionId !== undefined && hero && chipTitle === undefined - const inert = firstDraft.busy || (sessionId === undefined - ? workspaces.phase !== 'ready' || !sessionsReady - : needsWorkspace) - // Owner availability takes precedence over a Session-specific model block. + // The placeholder chip ("Choose workspace") and the Workspace-trigger input travel + // together: no workspace picked yet (cold start, no session at all), or a + // blank session whose workspace vanished (deleted from the sidebar). The + // bar is ONE session-maybe slot rendered unconditionally — inert is a prop, + // not a different tree, so the textarea DOM survives the transition. + const inert = sessionId === undefined || (hero && chipTitle === undefined) + // A raised block is the same inert posture with the blocker's own reason: + // one disabled textarea, never a second tree. The no-workspace state wins + // when both hold — picking a workspace is the earlier prerequisite. const blocked = !inert && composerBlock !== undefined const inputBar = renderSlot('conversation.composer.bar', { variant: hero ? 'hero' : 'composer', ...(inert ? { disabled: true, - placeholder: t(firstDraft.busy ? 'placeholder.preparing' : 'placeholder.workspace'), + placeholder: t('placeholder.workspace'), workspacePickerOpen: pickerOpen, - ...(needsWorkspace ? { onRequestWorkspace: () => { setPickerOpen(true) } } : {}), + onRequestWorkspace: () => { setPickerOpen(true) }, } : blocked // `blocked`, not `disabled`: the bar refuses input either way, but a @@ -192,23 +191,6 @@ export function ConversationContent(props: ConversationContentProps) { {composerSeat} - - - - - )} - > - {t('defaultWorkspace.retry')} - ) } diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.tsx index f66ee7a96a..c57fe69936 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.tsx @@ -1,5 +1,6 @@ -// Resident conversation shell keeps the composer mounted across local-draft, -// blank-Session, and active-conversation views. +// Resident conversation skeleton. Hero chrome, composer positioning, the +// chain, AND the composer bar (session-maybe slot) stay mounted across +// no-session/session transitions — the bar renders inert via owner props. import type { ConversationSlotProps } from '../contract/slots.ts' import { ConversationMainPanel } from './ConversationMainPanel.tsx' diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx index 5852e4b5c4..6a4ea12740 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx @@ -1,12 +1,16 @@ /** The default composer body: the 'conversation.composer.bar' slot entry. - * The injected input state and keyboard address the current Session or the - * first-use local draft. Standard Session props supply attachment actions; - * owner props control layout and availability. + * Machine state arrives through the standard provide channel + * (useInput + inputActions); the keyboard/DOM command face and stop arrive + * through this entry's own inject, whose hooks compartment binds + * useNotices/useLexicon; layout-phase inputs (variant and placeholder) ride + * the owner props. Session facts + * (running/removed/promptError) are self-selected via useSession. * * The text surface is the shell-owned Lexical editor bound here through * ComposerContentEditable; chips render as decorator portals, and the * keymap registers submit/menu/paste gestures on the editor command layer. - * The contenteditable remains mounted when the first Session arrives. + * The no-session state renders the SAME div inert as the Workspace-picker + * trigger instead of a parallel tree. */ import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react' @@ -38,7 +42,7 @@ import css from './InputBar.module.css' export type InputBarProps = ComposerBarProps export const InputBar = memo(function InputBar({ - useSession, useComposerInput, inputActions, keyboard, addFiles, removeAttachment, resolveDraftAttachments, + useSession, useInput, inputActions, keyboard, addFiles, removeAttachment, resolveDraftAttachments, retryFileUpload, toggleCommandMenu, stop, t, renderSlot, useBusyEnter, useFileUploads, useNotices, useLexicon, useMenuLauncher, @@ -46,7 +50,7 @@ export const InputBar = memo(function InputBar({ workspacePickerOpen = false, onRequestWorkspace, placeholder, accessory, }: InputBarProps) { - const input = useComposerInput(s => s) + const input = useInput(s => s) const notice = useNotices(s => s) const busyEnter = useBusyEnter(s => s) void useLexicon // hook seat stays bound by the inject compartment; text-ref decoration rides the shell's editor transforms @@ -60,11 +64,14 @@ export const InputBar = memo(function InputBar({ const planActive = useProjection('plan', plan => plan !== undefined && (plan.pending ? !plan.active : plan.active)) // Absent (undefined: no frame yet) and cleared (null) both mean no goal. const hasGoal = useProjection('goal', goal => goal != null) - const draft = input.draft - const editor = keyboard.editor + // Session-maybe: the machine faces are absent together while no session is + // current; the bar renders the same DOM inert instead of a parallel tree. + const live = input !== undefined && keyboard !== undefined && inputActions !== undefined + const draft = input?.draft ?? '' + const editor = keyboard?.editor ?? null const attachments = useMemo( - () => resolveDraftAttachments === undefined ? [] : resolveDraftAttachments(input.attachmentIds), - [resolveDraftAttachments, input.attachmentIds], + () => input === undefined || resolveDraftAttachments === undefined ? [] : resolveDraftAttachments(input.attachmentIds), + [resolveDraftAttachments, input?.attachmentIds], ) const empty = draft.trim() === '' && attachments.length === 0 const uploads = useFileUploads(snapshot => snapshot) @@ -86,7 +93,8 @@ export const InputBar = memo(function InputBar({ // The deployment's image-intake limits (absent while no attachment service // is composed — the pre-check below then defers entirely to the host). const imageLimits = useProjection('imageLimits') - // The toast announces promptError, the draft stays in the machine, + // Prompt failures are ordinary failures (no create/attach transaction exists + // anymore): the toast announces promptError, the draft stays in the machine, // and the user resubmits. A remount over a session whose machine still holds // an unresolved promptError deliberately re-announces it once — the failure // is still pending, and a transient banner is its only surface. Attachment @@ -114,30 +122,35 @@ export const InputBar = memo(function InputBar({ // but its independent Stop below stays available while it runs. const continuable = subagent?.address.mode === 'continuable' const parentOffline = continuable && subagent.parentAvailable !== true - // Preparation, removed Sessions, and unavailable parents lock editing. - // Adjudicating and submitting keep the draft visible and read-only. - const disabled = removed || inert || blocked !== undefined || parentOffline + // Running input stays free; locked = session removed, the + // inert no-workspace state, the machine faces absent (no session), or a + // parent-offline continuable child. An owner block also disables input; + // adjudicating and submitting render read-only so the draft stays visible. + const disabled = removed || inert || !live || blocked !== undefined || parentOffline const locked = disabled // The model seat is the ONE control a block leaves live: every block this // contract has is cleared by choosing a model, so locking it too would leave // the composer asking for the only thing it prevents. The other reasons to // be disabled do lock it — there is no session to choose a model for. - const modelSeatLocked = removed || inert - const machineBusy = input.phase === 'adjudicating' || input.phase === 'submitting' - // A blank Session whose Workspace was deleted offers directory selection - // through the same resident input node. + const modelSeatLocked = removed || inert || !live + const machineBusy = input?.phase === 'adjudicating' || input?.phase === 'submitting' + // The no-workspace surface remains the resident DOM node but acts as the + // existing picker trigger. Message controls stay locked until a Session + // exists; the trigger itself is read-only rather than disabled so pointer + // and keyboard users can reach the recovery action. const workspaceTrigger = inert && !removed && onRequestWorkspace !== undefined const editorDisabled = removed || (locked && !workspaceTrigger) - const editable = !locked && !machineBusy + const editable = live && !locked && !machineBusy const steeringAvailable = subagent === null || subagent.address.mode === 'continuable' const canSteerQueue = !locked && !machineBusy && !commandMenuOpen && empty && running && steeringAvailable && input.queue.length > 0 useEffect(() => { - if (inputActions !== undefined && attachments.length !== input.attachmentIds.length) { + if (input === undefined || inputActions === undefined) return + if (attachments.length !== input.attachmentIds.length) { inputActions.pruneAttachments(attachments.map(attachment => attachment.id)) } - }, [attachments, input.attachmentIds, inputActions]) + }, [attachments, input?.attachmentIds, inputActions]) // Scroll the draft scrollport the minimum that brings the selection focus // into view — the browser's own behavior for typing, performed for the @@ -154,7 +167,7 @@ export const InputBar = memo(function InputBar({ // is ours to perform — switching to a longer draft otherwise leaves the // caret (restored at the draft's end) off screen. useEffect(() => { - if (locked) return + if (locked || editor === null) return focusDraftEditor(editor, revealSelection) }, [locked, sessionId, editor]) @@ -231,10 +244,12 @@ export const InputBar = memo(function InputBar({ } useEffect(() => { + if (keyboard === undefined) return return installDraftFilePicker(keyboard, gate, fileInputRef) }, [keyboard]) useEffect(() => { + if (editor === null || keyboard === undefined) return return installDraftKeymap(editor, keyboard, gate) }, [editor, keyboard]) @@ -247,16 +262,17 @@ export const InputBar = memo(function InputBar({ } const onToggleCommandMenu = (): void => { + if (keyboard === undefined) return // The menu is a combobox over the editor, so the keyboard has to be there // before the launcher opens it: activating the button from the keyboard // leaves focus on the button, and restoring it afterwards would re-track an // empty draft and close the menu again. - focusDraftEditor(editor, revealSelection) + if (editor !== null) focusDraftEditor(editor, revealSelection) toggleCommandMenu?.(keyboard.caretSpan()) } - // When a blank Session loses its Workspace, the resident editable div acts as the - // picker trigger for keyboard users. + // The no-session Workspace trigger: the resident editable div acts as the + // picker trigger for keyboard users (no editor is bound in this state). const onWorkspaceKeyDown = (e: KeyboardEvent): void => { if (!workspaceTrigger) return if (e.key === 'Enter' || e.key === ' ') { @@ -279,7 +295,7 @@ export const InputBar = memo(function InputBar({ const primaryDisabled = primaryStops ? stop === undefined : empty || disabled || machineBusy || uploadsPending const interruptible = running && continuable const primarySubmitMode = resolveSubmitMode(busyEnter, running, 'enter', steeringAvailable) - const plainMessageDraft = !empty && input.phase === 'plain' && !draft.trimStart().startsWith('/') + const plainMessageDraft = !empty && input?.phase === 'plain' && !draft.trimStart().startsWith('/') const primaryLabel = primaryStops ? t('input.stop') : running && steeringAvailable && !disabled && !uploadsPending && plainMessageDraft @@ -290,6 +306,7 @@ export const InputBar = memo(function InputBar({ stop?.() return } + if (keyboard === undefined) return // absent machine: the button is disabled /* v8 ignore next -- defensive: the primary button is disabled for empty, disabled, and pending-upload states. */ if (!empty && !disabled && !machineBusy && !uploadsPending) keyboard.submit(primarySubmitMode) } @@ -297,7 +314,7 @@ export const InputBar = memo(function InputBar({ // Claim ghost hint: rendered by CSS as generated content after the last // paragraph while the claim's args are blank (a hint implies a single-line // token draft). The translated per-command hint wins over the claim's own. - const claimActive = (input.phase === 'claimed' || input.phase === 'submitting') + const claimActive = (input?.phase === 'claimed' || input?.phase === 'submitting') && input.claim !== undefined && draft.startsWith(input.claim.token) const rawHint = claimActive && input.claim.hint !== undefined && draft.slice(input.claim.token.length).trim() === '' @@ -305,7 +322,7 @@ export const InputBar = memo(function InputBar({ : null const hint = ((): string | null => { if (rawHint === null) return null - const commandName = input.claim?.name ?? '' + const commandName = input?.claim?.name ?? '' const hintKey = `hint.${commandName === 'goal' && hasGoal ? 'goal.active' : commandName}` // Dynamic lookup by claimed command name: unknown commands miss the // dictionary and keep the machine's own hint, so the call is wide. @@ -379,7 +396,7 @@ export const InputBar = memo(function InputBar({ scrollRef={scrollRef} editable={editable} editorDisabled={editorDisabled} - phase={input.phase} + phase={input?.phase ?? 'inert'} placeholderText={placeholderText} ariaLabel={workspaceTrigger ? t('hero.chooseWorkspace') : placeholderText} workspaceTrigger={workspaceTrigger} @@ -416,12 +433,12 @@ export const InputBar = memo(function InputBar({ {sessionId === undefined ? null : renderSlot('conversation.input.permission', { locked })} {sessionId === undefined ? null : renderSlot('conversation.input.plan', { locked })} - {sessionId === undefined + {input === undefined || sessionId === undefined ? null : renderSlot('conversation.input.left', {})}
- {sessionId === undefined + {input === undefined || sessionId === undefined ? null : renderSlot('conversation.input.right', {})} {sessionId === undefined ? null : renderSlot('conversation.input.model', { locked: modelSeatLocked })} @@ -465,7 +482,7 @@ export const InputBar = memo(function InputBar({
- {variant === 'composer' && sessionId !== undefined + {variant === 'composer' && input !== undefined && sessionId !== undefined ? renderSlot('conversation.composer.dock', {}) : null} diff --git a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx index 0339ef042d..e90a11a163 100644 --- a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx @@ -2,7 +2,6 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { describe, expect, it, onTestFinished, vi } from 'vitest' import type { CommandContribution, CommandUiContract } from '@deepseek-ai/dsh-client-ui-commands/client' -import type { UiWorkspace } from '@deepseek-ai/dsh-client-ui-workspace/client' import type { ISession, SessionReference } from '@deepseek-ai/dsh-api-session-controller/client' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' @@ -74,14 +73,12 @@ async function bench() { opened(id) } const openSession = vi.fn((id: SessionId) => { replaceMain(id) }) - const openDefaultWorkspace = vi.fn(async () => undefined) runtime.ctx.provide('uiWorkspace', { openWorkspace: async (_workspaceId: WorkspaceId, beforeOpen: (id: SessionId) => void) => { const id = await connectWorkspace() replaceMain(id, beforeOpen) }, openSession, - openDefaultWorkspace, } as never) const sessionFake = sessionFakeFor() await runtime.sessions.add({ @@ -139,113 +136,10 @@ async function bench() { return { runtime, feature, slots: runtime.slots, entryOf, conversationApi, headerApi, residentApi, composerApi, inputApi, viewSource, sessionFake, connectWorkspace, rootUpload, uploads, rootReference, references, opened, - locale, openDefaultWorkspace, replaceMain, } } describe('Conversation inject API', () => { - it.each([false, true])('keeps the saved first draft after its Session retires (reopened during preparation: %s)', async (reopenEarly) => { - const b = await bench() - onTestFinished(() => b.runtime.dispose()) - const settings = Promise.withResolvers() - const started = Promise.withResolvers() - b.runtime.ctx.on('conversation/prepare-first-send', () => { - started.resolve(undefined) - return settings.promise - }) - b.openDefaultWorkspace.mockImplementation(async (_request, beforeOpen) => { - b.replaceMain(ROOT, beforeOpen) - return ROOT - }) - const body = b.conversationApi(ROOT) - const unmirror = body.injected.bindDraftMirror(body.instance.actions.setDraft) - const composer = b.composerApi(undefined) - let reopened: SessionReference | undefined - try { - composer.keyboard.paste('keep this first draft') - composer.keyboard.submit('queue') - await started.promise - expect(body.instance.store.getSnapshot().draft).toBe('keep this first draft') - const other = 'other-first-send' as SessionId - await b.runtime.sessions.add({ id: other, session: sessionFakeFor() }) - unmirror() - b.rootReference.release() - b.replaceMain(other) - await vi.waitFor(() => { expect(b.runtime.sessions.binding(ROOT)).toBeUndefined() }) - if (reopenEarly) reopened = b.runtime.sessions.retain(ROOT) - settings.resolve(undefined) - await vi.waitFor(() => { expect(b.residentApi(undefined).hooks.firstDraft.getSnapshot().busy).toBe(false) }) - await b.runtime.flush() - expect(b.sessionFake.prompt).not.toHaveBeenCalled() - reopened ??= b.runtime.sessions.retain(ROOT) - b.references.set(ROOT, reopened) - expect(b.conversationApi(ROOT).instance.store.getSnapshot().draft).toBe('keep this first draft') - expect(composer.hooks.composerInput.getSnapshot().draft).toBe('') - } finally { - settings.resolve(undefined) - reopened?.release() - unmirror() - } - }) - - it('submits the first draft through its retained destination input', async () => { - const b = await bench() - onTestFinished(() => b.runtime.dispose()) - b.openDefaultWorkspace.mockImplementation(async (_request, beforeOpen) => { - b.replaceMain(ROOT, beforeOpen) - return ROOT - }) - const composer = b.composerApi(undefined) - composer.keyboard.paste('first message') - composer.keyboard.submit('queue') - await vi.waitFor(() => { expect(b.sessionFake.prompt).toHaveBeenCalledOnce() }) - expect(b.sessionFake.prompt.mock.calls[0]?.[0]).toEqual([{ type: 'text', text: 'first message' }]) - expect(composer.hooks.composerInput.getSnapshot().draft).toBe('') - }) - - it.each([ - ['zh', '默认工作区', '默认工作区'], - ['en', 'Default workspace', 'Default workspace'], - ['ja', 'default-workspace', 'Default workspace'], - ])('resolves first-use names in the Client using the send-time locale %s', async (language, directoryName, title) => { - const b = await bench() - if (language === 'ja') b.locale.addLanguage({ id: 'ja', label: '日本語', fallback: 'en' }) - const composer = b.composerApi(undefined) - composer.keyboard.paste('first message') - b.locale.setLocale(language) - composer.keyboard.submit('steer') - await vi.waitFor(() => { - expect(b.openDefaultWorkspace).toHaveBeenCalledWith({ directoryName, title }, expect.any(Function), expect.any(AbortSignal)) - expect(b.residentApi(undefined).hooks.firstDraft.getSnapshot().busy).toBe(false) - }) - }) - - it('keeps in-flight names fixed and resolves the new locale when retrying a failed first send', async () => { - const b = await bench() - const pending = Promise.withResolvers() - b.openDefaultWorkspace.mockReturnValueOnce(pending.promise) - const composer = b.composerApi(undefined) - b.locale.setLocale('en') - composer.keyboard.paste('keep this draft') - composer.keyboard.submit('steer') - try { - await vi.waitFor(() => { expect(b.openDefaultWorkspace).toHaveBeenCalledOnce() }) - b.locale.setLocale('zh') - expect(b.openDefaultWorkspace.mock.calls[0]?.[0]).toEqual({ directoryName: 'Default workspace', title: 'Default workspace' }) - pending.reject(new Error('directory unavailable')) - await vi.waitFor(() => { expect(b.residentApi(undefined).hooks.firstDraft.getSnapshot().busy).toBe(false) }) - expect(composer.hooks.composerInput.getSnapshot().draft).toBe('keep this draft') - composer.keyboard.submit('steer') - await vi.waitFor(() => { - expect(b.openDefaultWorkspace).toHaveBeenLastCalledWith({ directoryName: '默认工作区', title: '默认工作区' }, expect.any(Function), expect.any(AbortSignal)) - expect(b.residentApi(undefined).hooks.firstDraft.getSnapshot().busy).toBe(false) - }) - } finally { - pending.resolve(undefined) - await vi.waitFor(() => { expect(b.residentApi(undefined).hooks.firstDraft.getSnapshot().busy).toBe(false) }) - } - }) - it('owns the File action, reads its mounted composer availability, and unregisters on disposal', async () => { const b = await bench() onTestFinished(() => b.runtime.dispose()) @@ -265,7 +159,7 @@ describe('Conversation inject API', () => { expect(file.available({ sessionId: 'missing' as SessionId })).toBe(false) if (file.ui.kind !== 'action') throw new Error('File must be an action') file.ui.run({ sessionId: 'missing' as SessionId }) - const keyboard = b.composerApi(ROOT).keyboard + const keyboard = b.composerApi(ROOT).keyboard! const open = vi.fn() let available = true const unbind = keyboard.bindFilePicker({ open, available: () => available }) @@ -514,8 +408,7 @@ describe('Conversation inject API', () => { expect(() => { injectBar('ghost' as SessionId).stop!() }).toThrow(/resolved no binding/) const absent = injectBar(undefined) - expect(absent.keyboard).toBeDefined() - expect(absent.hooks.composerInput.getSnapshot().draft).toBe('') + expect(absent.keyboard).toBeUndefined() expect(absent.toggleCommandMenu).toBeUndefined() expect(absent.stop).toBeUndefined() expect(absent.hooks.notices.getSnapshot()).toBeNull() diff --git a/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx b/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx index 51513cb28e..84e5ba28a1 100644 --- a/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx +++ b/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx @@ -100,10 +100,8 @@ async function bench(opts?: { blank?: boolean }) { } describe('resident composer', () => { - it('accepts a local draft before any Session exists and keeps the Workspace chip available', async () => { + it('renders the locked view state while no session exists at all', async () => { const runtime = await SlotTestRuntime.create() - runtime.sessions.list.set({ ...runtime.sessions.list.getSnapshot(), phase: 'pending' }) - await runtime.workspaces.update((draft) => { draft.phase = 'pending' }) provideWorkspaceNavigation(runtime) runtime.ctx.provide('settingsScope', { developerTools: { enabled: createSnapshotStore(true) }, bind: () => stubSettingsScope().scope } as never) const locale = new LocaleRuntime(runtime.ctx) @@ -115,21 +113,15 @@ describe('resident composer', () => { const view = runtime.renderRoot() const textarea = view.container.querySelector('[data-composer-input]') expect(textarea).not.toBeNull() - expect(textarea!.getAttribute('contenteditable')).toBe('false') - await runtime.workspaces.update((draft) => { draft.phase = 'ready' }) - expect(textarea!.getAttribute('contenteditable')).toBe('false') - await act(async () => { - runtime.sessions.list.set({ ...runtime.sessions.list.getSnapshot(), phase: 'ready' }) - }) expect(textarea!.getAttribute('aria-disabled')).not.toBe('true') - expect(textarea!.getAttribute('contenteditable')).toBe('true') - expect(textarea!.getAttribute('aria-haspopup')).toBeNull() + expect(textarea!.getAttribute('contenteditable')).not.toBe('true') + expect(textarea!.getAttribute('aria-haspopup')).toBe('menu') expect(view.getByTestId('workspace-probe').textContent).toBe('false:0') - fireEvent.click(view.getByRole('button', { name: '选择工作区' })) + fireEvent.click(textarea!) expect(view.getByTestId('workspace-probe').textContent).toBe('true:0') - expect(textarea!.getAttribute('aria-expanded')).toBeNull() - fireEvent.click(view.getByRole('button', { name: '选择工作区' })) + expect(textarea!.getAttribute('aria-expanded')).toBe('true') fireEvent.click(view.getByRole('button', { name: '选择工作区' })) + fireEvent.keyDown(textarea!, { key: 'Enter' }) expect(view.getByTestId('workspace-probe').textContent).toBe('true:0') expect(view.getByRole('button', { name: '选择工作区' })).toBeTruthy() await runtime.dispose() @@ -157,7 +149,7 @@ describe('resident composer', () => { const workspaceChip = view.getByRole('button', { name: '选择工作区' }) const workspaceProbe = view.getByTestId('workspace-probe') expect(textarea.getAttribute('aria-disabled')).not.toBe('true') - expect(textarea.getAttribute('contenteditable')).toBe('true') + expect(textarea.getAttribute('contenteditable')).not.toBe('true') fireEvent.click(workspaceChip) fireEvent.click(workspaceProbe) diff --git a/packages/client/ui-conversation/tests/first-draft.client.spec.ts b/packages/client/ui-conversation/tests/first-draft.client.spec.ts deleted file mode 100644 index b23055dcf1..0000000000 --- a/packages/client/ui-conversation/tests/first-draft.client.spec.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { Context } from '@deepseek-ai/cordis' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { SessionId } from '@deepseek-ai/dsh-session/types' -import { FirstDraft } from '../src/client/input/first-draft.ts' -import { SessionInputShell } from '../src/client/input/facade.ts' -import type { SubmitOutcome } from '../src/client/contract/input.ts' - -const contexts: Context[] = [] -afterEach(async () => { - for (const ctx of contexts.splice(0)) await ctx.fiber.dispose() -}) - -function harness() { - const ctx = new Context() - contexts.push(ctx) - const opened = Promise.withResolvers() - ctx.effect(() => () => { opened.resolve(undefined) }) - const submitted = vi.fn(async (): Promise => ({ kind: 'success' })) - const target = new SessionInputShell({ - actx: ctx, - defaultSink: submitted, - commandAttachments: { serialize: async () => [], release: () => {}, unsupportedNotice: () => '' }, - }) - ctx.effect(() => () => { target.dispose() }) - let beforeOpen: ((id: SessionId) => void) | undefined - const open = vi.fn((prepare: (id: SessionId) => void) => { - beforeOpen = prepare - return opened.promise - }) - const first = new FirstDraft(ctx, { open, shell: () => target, isCurrent: () => true }) - return { - ctx, first, target, submitted, open, opened, - complete: () => { - const id = SessionId('default') - beforeOpen!(id) - opened.resolve(id) - }, - } -} - -describe('first message draft', () => { - it('retains a local draft without opening a Session until send', async () => { - const h = harness() - h.first.shell.setDraft('first message') - expect(h.open).not.toHaveBeenCalled() - h.first.shell.submit('steer') - expect(h.open).toHaveBeenCalledTimes(1) - expect(h.first.state.getSnapshot().busy).toBe(true) - h.first.shell.submit('steer') - expect(h.open).toHaveBeenCalledTimes(1) - h.complete() - await vi.waitFor(() => { expect(h.submitted).toHaveBeenCalledTimes(1) }) - expect(h.submitted.mock.calls[0]).toEqual(['first message', [], 'steer', expect.any(AbortSignal)]) - expect(h.first.state.getSnapshot()).toEqual({ busy: false, failed: false }) - }) - - it.each([false, true])('waits for first-use settings and keeps the Session draft on refusal (refused: %s)', async (refused) => { - const h = harness() - const settings = Promise.withResolvers() - const started = Promise.withResolvers() - h.ctx.on('conversation/prepare-first-send', (id) => { - started.resolve(id) - return settings.promise - }) - try { - h.first.shell.setDraft('use my selected mode') - h.first.shell.submit() - h.complete() - expect(await started.promise).toBe(SessionId('default')) - expect(h.submitted).not.toHaveBeenCalled() - if (refused) settings.reject(new Error('preset refused')) - else settings.resolve(undefined) - await vi.waitFor(() => { expect(h.first.state.getSnapshot().busy).toBe(false) }) - expect(h.first.state.getSnapshot().failed).toBe(false) - if (refused) { - expect(h.submitted).not.toHaveBeenCalled() - expect(h.target.snapshot.draft).toBe('use my selected mode') - expect(h.target.notices.getSnapshot()?.text).toBe('preset refused') - } else { - expect(h.submitted).toHaveBeenCalledOnce() - } - } finally { - settings.resolve(undefined) - await vi.waitFor(() => { expect(h.first.state.getSnapshot().busy).toBe(false) }) - } - }) - - it('restores input on preparation failure and dismisses the modal without losing it', async () => { - const h = harness() - h.first.shell.setDraft('preserve me') - h.first.shell.submit() - h.opened.reject(new Error('permission denied')) - await vi.waitFor(() => { expect(h.first.shell.snapshot.draft).toBe('preserve me') }) - expect(h.first.state.getSnapshot()).toEqual({ busy: false, failed: true }) - expect(h.submitted).not.toHaveBeenCalled() - h.first.dismiss() - expect(h.first.state.getSnapshot().failed).toBe(false) - expect(h.first.shell.snapshot.draft).toBe('preserve me') - }) - - it('hands a draft to a manual selection without sending it', async () => { - const h = harness() - h.first.shell.setDraft('manual folder') - h.first.transfer(SessionId('manual')) - expect(h.target.snapshot.draft).toBe('manual folder') - expect(h.first.shell.snapshot.draft).toBe('') - expect(h.submitted).not.toHaveBeenCalled() - }) - - it('lets manual navigation take the pending draft and cancels automatic submission', async () => { - const h = harness() - h.first.shell.setDraft('pending text') - h.first.shell.submit() - h.first.transfer(SessionId('manual')) - h.opened.resolve(undefined) - await vi.waitFor(() => { expect(h.first.state.getSnapshot().busy).toBe(false) }) - expect(h.target.snapshot.draft).toBe('pending text') - expect(h.first.shell.snapshot.draft).toBe('') - expect(h.submitted).not.toHaveBeenCalled() - }) - - it('restores a superseded draft without a directory error', async () => { - const h = harness() - h.first.shell.setDraft('later') - h.first.shell.submit() - h.opened.resolve(undefined) - await vi.waitFor(() => { expect(h.first.shell.snapshot.draft).toBe('later') }) - expect(h.first.state.getSnapshot().failed).toBe(false) - }) - - it('leaves ordinary send failures in the selected Session input', async () => { - const h = harness() - h.submitted.mockResolvedValue({ kind: 'error' }) - h.first.shell.setDraft('retry the prompt') - h.first.shell.submit() - h.complete() - await vi.waitFor(() => { expect(h.target.snapshot.draft).toBe('retry the prompt') }) - expect(h.first.shell.snapshot.draft).toBe('') - expect(h.first.state.getSnapshot().failed).toBe(false) - }) -}) diff --git a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx index a4805db1ec..9e0366952c 100644 --- a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx @@ -185,7 +185,6 @@ function bench(over?: BenchOptions) { ? over?.plan : key === 'goal' ? over?.goal : key === 'imageLimits' ? over?.imageLimits : undefined)), - useComposerInput: bindSnapshotSelector(shell.state), useInput: bindSnapshotSelector(shell.state), inputActions: shell.actions, keyboard: shell, diff --git a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx index c8641afcb4..15d87a0ca7 100644 --- a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx @@ -67,7 +67,6 @@ function mountBar(shell: SessionInputShell, over?: { running?: boolean; disabled })), useProjection: (() => undefined), useConversation: bindSnapshotSelector(createSnapshotStore(conversationSnapshot())), - useComposerInput: bindSnapshotSelector(shell.state), useInput: bindSnapshotSelector(shell.state), inputActions: shell.actions, keyboard: shell, diff --git a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx index 0c098d95fb..347b4d05c1 100644 --- a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx @@ -161,7 +161,6 @@ async function scopedBench(register?: (inputTriggers: InputTriggerService) => vo })), useProjection: (() => undefined), useConversation: bindSnapshotSelector(createSnapshotStore(conversationSnapshot())), - useComposerInput: bindSnapshotSelector(shell.state), useInput: bindSnapshotSelector(shell.state), inputActions: shell.actions, keyboard: shell, diff --git a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx index 619e3fddff..17aadfb056 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -137,8 +137,6 @@ function mount( nestedSubagent?: boolean /** A composer block another plugin raised for this session. */ composerBlock?: { reason: string } - /** First-use preparation remains active after selecting its Session. */ - preparingFirstDraft?: boolean /** Mutable view ledger used by registration-order regressions. */ viewTabs?: ViewTab[] } = {}, @@ -282,7 +280,6 @@ function mount( useProjection={(() => undefined)} useInput={useInput} inputActions={inputActions} - useComposerInput={useInput} keyboard={wiring} addFiles={() => null} useFileUploads={bindSnapshotSelector(createSnapshotStore({}))} @@ -339,8 +336,6 @@ function mount( useWorkspaces: bindSnapshotSelector(workspaces), useProjection: (() => undefined), useComposerBlock: select => select(options.composerBlock), - useFirstDraft: select => select({ busy: options.preparingFirstDraft === true, failed: false }), - dismissDefaultFailure: () => {}, useInput, inputActions, renderSlot, @@ -410,18 +405,6 @@ describe('ConversationRoot resident composer', () => { expect(b.view.queryByTestId('view-conversation.session.header.corner')).toBeNull() }) - it('locks the selected Session draft until automatic first-use preparation settles', () => { - const b = mount(sessionSnapshotOf({ blank: true }), undefined, undefined, { - summaryBlank: true, preparingFirstDraft: true, - }) - const box = b.view.getByRole('textbox') - expect(box.getAttribute('aria-disabled')).toBe('true') - expect(box.getAttribute('aria-label')).toBe('正在准备工作区…') - expect(box.getAttribute('aria-haspopup')).toBeNull() - fireEvent.keyDown(box, { key: 'Enter' }) - expect(b.sink).not.toHaveBeenCalled() - }) - it('does not redispatch composer child slots for an unrelated Session publication', () => { const b = mount(sessionSnapshotOf()) const childKeys = new Set([ diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index b98485e434..4af8adc8d4 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-workspace/README.md -README.md: 03dc8a9ff45fbc1fc1ab8585db15c19437807f5e -README.zh.md: ac8000f78d3a9394ec2c83790aa3e0349cac2ab0 +README.md: 768c66503af70d0b587b25c09aa8412b0a647439 +README.zh.md: 25df6f8e6a2ec0a001d784c7bde18e454e9d706f diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index 03dc8a9ff4..768c66503a 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -69,7 +69,9 @@ The value is intentionally best effort for cold Sessions. An identity-matching u New Session tries to acquire the first eligible blank in catalog order; startup restoration tries the saved blank. If that writer is held, navigation creates a new Session without trying other blanks. Other acquisition failures abort the request and are currently reported only to the console. Released blanks retain their slash-command state when reused. Later navigation cancels a pending startup selection. -`openDefaultWorkspace(request, beforeOpen, signal)` initializes the Host default Workspace from the requested directory name and title before connecting its Session. It captures navigation cancellation before directory preparation; superseded work cannot transfer the draft or select its Session. A successfully registered Workspace remains available when Session creation or later submission fails. [Conversation](../ui-conversation/README.md) owns the first-use draft and failure dialog. +Once both Workspace and Session startup baselines are ready, an empty installation calls `workspaces.initializeDefault` and creates or reuses its blank Session. The composer becomes editable when that Session is selected; no message is submitted automatically. Later navigation or owner disposal prevents startup from selecting its result. Ineligible first use leaves the folder picker available without an error. Preparation failure offers Cancel or Choose folder through the existing picker, and is not retried until the next startup. A successfully registered Workspace remains available when Session creation or later submission fails. + +The Client chooses the initial directory name and title from its language at startup: Chinese uses `默认工作区`, English uses `Default workspace`, and other languages use directory `default-workspace` with title `Default workspace`. The request retains those names during initialization. A successfully initialized Workspace keeps its directory and title across language changes. ## Understand the implementation diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index ac8000f78d..25df6f8e6a 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -69,7 +69,9 @@ Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示** 新建会话尝试获取列表中第一个符合条件的空白会话;启动恢复尝试已保存的空白会话。若该写锁被占用,导航直接新建 Session,不再尝试其他空白会话。其他获取错误会中止请求,目前只报告到控制台。已释放的空白会话被复用时保留 slash 命令状态。后续导航会取消尚未完成的启动选择。 -`openDefaultWorkspace(request, beforeOpen, signal)` 在连接 Session 前,按请求中的目录名和标题初始化 Host 默认工作区。它在目录准备之前捕获导航取消信号;被取代的操作不能转移草稿或选中 Session。登记成功的工作区在 Session 创建或后续提交失败时仍然保留。[Conversation](../ui-conversation/README.zh.md) 负责首次使用草稿和失败弹窗。 +Workspace 和 Session 的启动基线均就绪后,空安装环境调用 `workspaces.initializeDefault`,创建或复用其空白 Session。选中该 Session 后输入框才可编辑,不会自动提交消息。后续导航或所属上下文销毁会阻止启动流程选中其结果。不符合首次使用条件时仍可选择文件夹,不显示错误。准备失败时通过现有选择器提供取消或选择文件夹操作,直到下次启动才重试。登记成功的工作区在 Session 创建或后续提交失败时仍然保留。 + +Client 在启动时按其语言选择初始目录名和标题:中文使用 `默认工作区`,英文使用 `Default workspace`,其他语言使用目录 `default-workspace` 和标题 `Default workspace`。初始化过程中保留请求中的名称。成功初始化的工作区在切换语言后保留原目录和标题。 ## 理解实现 diff --git a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx index b74e3689dc..42e177afce 100644 --- a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx +++ b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx @@ -231,21 +231,45 @@ export function WorkspacePicker({ onClose, createWorkspace, useDirectoryFlow, + useDefaultFailure, + dismissDefaultFailure, renderSlot, t, }: WorkspacePickerProps) { + const failed = useDefaultFailure(value => value) + const flowAvailable = useDirectoryFlow(value => value) + const [recovering, setRecovering] = useState(false) return ( - renderSlot('conversation.hero.workspace.directoryFlow', owner)} - selectedId={selectedId} - onPick={onPick} - onClose={onClose} - /> + <> + renderSlot('conversation.hero.workspace.directoryFlow', owner)} + selectedId={selectedId} + onPick={onPick} + onClose={() => { setRecovering(false); onClose() }} + /> + + + + + )} + > + {t('defaultWorkspace.retry')} + + ) } diff --git a/packages/client/ui-workspace/src/client/contract/slots.ts b/packages/client/ui-workspace/src/client/contract/slots.ts index 6a54d79146..b878e24986 100644 --- a/packages/client/ui-workspace/src/client/contract/slots.ts +++ b/packages/client/ui-workspace/src/client/contract/slots.ts @@ -364,6 +364,12 @@ export type WorkspaceBrowserProps = * supplies the implicit index signature required by the registry. */ export type WorkspacePickerInjected = DirectoryPickingInjected & { + /** Dismiss the startup failure before choosing a directory manually. */ + dismissDefaultFailure: () => void + hooks: { + /** Whether first-use startup failed to prepare a Workspace and Session. */ + defaultFailure: HostObservable + } /** Adopt a picked host directory as a real Workspace before targeting a Session. */ createWorkspace: (input: { path: string }) => Promise } @@ -377,5 +383,5 @@ export type WorkspacePickerProps = PropsRuntime<'conversation.hero.workspace'> & PropsRenderSlots<'conversation.hero.workspace.directoryFlow'> & Omit - & DirectoryPickingHooks + & PropsHooks & PropsLocale<'workspace'> diff --git a/packages/client/ui-workspace/src/client/index.ts b/packages/client/ui-workspace/src/client/index.ts index 0614dea6a4..8d96c65d77 100644 --- a/packages/client/ui-workspace/src/client/index.ts +++ b/packages/client/ui-workspace/src/client/index.ts @@ -219,7 +219,8 @@ export function apply(ctx: Context): void { }) const pickerInjected = (): WorkspacePickerInjected => ({ createWorkspace: input => workspaces.create(input), - hooks: { directoryFlow: pickerFlowSource }, + dismissDefaultFailure: () => { uiWorkspace.defaultFailure.set(false) }, + hooks: { directoryFlow: pickerFlowSource, defaultFailure: uiWorkspace.defaultFailure }, }) // Each registration declares its owned children in the same call; slot // injection follows both the owner and declaration HMR lifetimes. diff --git a/packages/client/ui-workspace/src/client/locales.ts b/packages/client/ui-workspace/src/client/locales.ts index e721af231f..d926ce987f 100644 --- a/packages/client/ui-workspace/src/client/locales.ts +++ b/packages/client/ui-workspace/src/client/locales.ts @@ -6,6 +6,10 @@ /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { + 'defaultWorkspace.failed': '无法创建默认工作区', + 'defaultWorkspace.title': '默认工作区', + 'defaultWorkspace.retry': '请选择一个文件夹后重试', + 'defaultWorkspace.choose': '选择文件夹', 'group.ungrouped': '未分组', 'session.new': '新会话', 'section.workspaces': '工作区', @@ -99,6 +103,10 @@ export type WorkspaceKey = keyof typeof zh /** English dictionary, checked complete against the zh key set. */ export const en = { + 'defaultWorkspace.failed': 'Unable to create default workspace', + 'defaultWorkspace.title': 'Default workspace', + 'defaultWorkspace.retry': 'Please choose a folder and try again', + 'defaultWorkspace.choose': 'Choose folder', 'group.ungrouped': 'Ungrouped', 'session.new': 'New Session', 'section.workspaces': 'Workspaces', diff --git a/packages/client/ui-workspace/src/client/navigation.ts b/packages/client/ui-workspace/src/client/navigation.ts index 29c4c8d3f7..b21cf06f15 100644 --- a/packages/client/ui-workspace/src/client/navigation.ts +++ b/packages/client/ui-workspace/src/client/navigation.ts @@ -12,10 +12,12 @@ import type { import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import type { - IWorkspaces, WorkspaceId, WorkspaceInitializeDefaultRequest, WorkspaceSnapshot, WorkspaceView, + IWorkspaces, WorkspaceId, WorkspaceSnapshot, WorkspaceView, } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' +import type {} from '@deepseek-ai/dsh-client-locale/client' +import { en, zh } from './locales.ts' import { pinOrderAccounts, pinOrderSource } from './pin-order.ts' import type { WorkspaceViewStoreActions } from './stores.ts' @@ -38,18 +40,6 @@ export interface UiWorkspace { * @returns completion; a superseded request may create a Session but does not open it. */ openWorkspace(workspaceId: WorkspaceId, beforeOpen?: (sessionId: SessionId) => void): Promise - /** - * Prepare the first-use Workspace and select its blank Session. - * @param request - initial directory name and title. - * @param beforeOpen - synchronous draft transfer after retaining the Session. - * @param signal - caller cancellation. - * @returns selected Session, or undefined after navigation supersession. - */ - openDefaultWorkspace( - request: WorkspaceInitializeDefaultRequest, - beforeOpen: (sessionId: SessionId) => void, - signal: AbortSignal, - ): Promise /** * Fork a Session without changing the current selection. * @param sessionId - source Session. @@ -130,6 +120,8 @@ export class DirectoryBrowseError extends Error { /** Implements Workspace archive and directory UI operations. */ class UiWorkspaceService extends Service implements UiWorkspace { + /** Startup failure awaiting dismissal or explicit directory selection. */ + readonly defaultFailure = createSnapshotStore(false) private readonly connecting = new Map>() private readonly lifetime = new AbortController() private readonly selection = createSnapshotStore( @@ -213,25 +205,6 @@ class UiWorkspaceService extends Service implements UiWorkspace { this.replaceMain(sessionId, navigation, 'reveal', beforeOpen) } - async openDefaultWorkspace( - request: WorkspaceInitializeDefaultRequest, - beforeOpen: (sessionId: SessionId) => void, - signal: AbortSignal, - ): Promise { - const navigation = AbortSignal.any([this.ctx.layout.beginNavigation(), this.lifetime.signal, signal]) - try { - const workspace = await this.workspaces.initializeDefault(request, navigation) - navigation.throwIfAborted() - const sessionId = await this.connectWorkspace(workspace.workspaceId) - navigation.throwIfAborted() - this.replaceMain(sessionId, navigation, 'reveal', beforeOpen) - return sessionId - } catch (error) { - if (navigation.aborted) return undefined - throw error - } - } - async forkSession(sessionId: SessionId): Promise { await this.sessions.fork({ sessionId, increaseTitle: true }) } @@ -353,11 +326,30 @@ class UiWorkspaceService extends Service implements UiWorkspace { } const target = workspace?.workspaceId ?? recentWorkspace(workspaces.items, sessions.byId) if (sessionId === undefined && target !== undefined) sessionId = await this.connectWorkspace(target) + if (target === undefined && workspaces.items.length === 0 && sessions.ids.length === 0) { + sessionId = await this.initializeDefaultWorkspace(navigation) + } if (sessionId !== undefined && !navigation.aborted) { this.replaceMain(sessionId, navigation, 'preserve') } } + private async initializeDefaultWorkspace(signal: AbortSignal): Promise { + const language = this.ctx.locale.getSnapshot().active.toLowerCase().split('-')[0] + const title = (language === 'zh' ? zh : en)['defaultWorkspace.title'] + try { + const workspace = await this.workspaces.initializeDefault({ + directoryName: language === 'zh' || language === 'en' ? title : 'default-workspace', + title, + }, signal) + if (workspace === undefined || signal.aborted) return undefined + return await this.connectWorkspace(workspace.workspaceId) + } catch (_error: unknown) { + if (!signal.aborted) this.defaultFailure.set(true) + return undefined + } + } + /** @returns true when an archived current selection was cleared. */ private clearArchivedCurrent(): boolean { const current = this.mainReference?.sessionId diff --git a/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx b/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx index 9ff0181207..e72d523668 100644 --- a/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx @@ -1,6 +1,7 @@ // @vitest-environment jsdom import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots' import { afterEach, describe, expect, it, vi } from 'vitest' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client' import type { @@ -88,14 +89,19 @@ function mount( items: readonly WorkspaceView[] = [workspace('alpha', 'Alpha')], createWorkspace = vi.fn(), occupancy = occupancySource(), + options: { defaultFailure?: boolean; open?: boolean } = {}, ) { + const failure = createSnapshotStore(options.defaultFailure ?? false) + const useDefaultFailure = bindSnapshotSelector(failure) + const dismissDefaultFailure = vi.fn(() => { failure.set(false) }) const onPick = vi.fn() const onClose = vi.fn() const anchorRef = anchor() const { probe, renderSlot } = flowProbe() const renderPicker = (nextItems: readonly WorkspaceView[]) => ( { view.rerender(renderPicker(nextItems)) }, } } @@ -220,6 +226,7 @@ describe('WorkspacePicker', () => { const { renderSlot } = flowProbe() render( undefined} @@ -238,6 +245,7 @@ describe('WorkspacePicker', () => { const { renderSlot } = flowProbe() render( undefined} @@ -321,3 +329,26 @@ describe('WorkspacePicker', () => { expect(screen.queryByRole('menuitem', { name: '添加工作区…' })).toBeNull() }) }) + +describe('default Workspace startup recovery', () => { + it('dismisses the failure without opening the directory flow', () => { + const b = mount([], vi.fn(), occupancySource(), { defaultFailure: true, open: false }) + expect(screen.getByRole('dialog', { name: '无法创建默认工作区' })).toBeTruthy() + expect(b.probe.owner?.open).toBe(false) + fireEvent.click(screen.getByRole('button', { name: '取消' })) + expect(b.dismissDefaultFailure).toHaveBeenCalledOnce() + expect(screen.queryByRole('dialog', { name: '无法创建默认工作区' })).toBeNull() + expect(b.probe.owner?.open).toBe(false) + }) + + it('opens the composed directory flow from the startup failure', async () => { + const create = vi.fn(async () => workspace('chosen')) + const b = mount([], create, occupancySource(), { defaultFailure: true, open: false }) + fireEvent.click(screen.getByRole('button', { name: '选择文件夹' })) + expect(b.dismissDefaultFailure).toHaveBeenCalledOnce() + expect(b.probe.owner?.open).toBe(true) + await act(async () => { b.probe.owner!.onPicked('/chosen') }) + expect(create).toHaveBeenCalledExactlyOnceWith({ path: '/chosen' }) + expect(b.onPick).toHaveBeenCalledExactlyOnceWith(wid('chosen')) + }) +}) diff --git a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts index 422de2dc2d..4f9cd973b8 100644 --- a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts +++ b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts @@ -1,4 +1,6 @@ +import { setImmediate } from 'node:timers/promises' import { Context } from '@deepseek-ai/cordis' +import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import { afterEach, describe, expect, it, vi } from 'vitest' import type { ISessions, SessionListState, SessionReference, SessionSummary, @@ -169,11 +171,7 @@ class FakeSessions implements ISessions { } class FakeWorkspaces implements IWorkspaces { - readonly initializeDefault = vi.fn(async () => { - const item = workspace('default') - this.list.set(workspaceState([item])) - return item - }) + readonly initializeDefault = vi.fn(async () => undefined) readonly list: MutableSource readonly archiveCalls: SessionId[] = [] readonly unarchiveCalls: SessionId[] = [] @@ -268,6 +266,8 @@ class FakeDirectoryPicker { } interface BenchOptions { + readonly language?: string + readonly configureWorkspaces?: (workspaces: FakeWorkspaces) => void readonly workspaces?: WorkspaceSnapshot readonly sessions?: SessionListState readonly configureSessions?: (sessions: FakeSessions) => void @@ -276,6 +276,10 @@ interface BenchOptions { function bench(options: BenchOptions = {}) { const ctx = new Context() contexts.push(ctx) + const locale = new LocaleRuntime(ctx) + if (options.language === 'fr') locale.addLanguage({ id: 'fr', label: 'Français', fallback: 'en' }) + locale.setLocale(options.language ?? 'en') + ctx.provide('locale', locale) const layout = new LayoutController({ selectPanel: vi.fn(), retainMainPanels: vi.fn(), setSidebar: vi.fn(), toggleSidebar: vi.fn(), setViewportWidth: vi.fn(), @@ -287,6 +291,7 @@ function bench(options: BenchOptions = {}) { const directoryPicker = new FakeDirectoryPicker() const workspaces = new FakeWorkspaces(options.workspaces ?? workspaceState([], [], 'pending')) const sessions = new FakeSessions(options.sessions ?? sessionState([], 'pending')) + options.configureWorkspaces?.(workspaces) options.configureSessions?.(sessions) const view = createWorkspaceViewStore().create() const uiWorkspace = new UiWorkspaceService( @@ -300,39 +305,95 @@ function bench(options: BenchOptions = {}) { } describe('UiWorkspaceService', () => { - it('prepares the default Workspace before creating and retaining its Session', async () => { - const b = bench({ workspaces: workspaceState(), sessions: sessionState() }) - const beforeOpen = vi.fn(() => { - expect(b.sessions.retain).toHaveBeenCalledWith(sid('created-default'), { source: 'mainView' }) + it.each([ + ['zh', '默认工作区', '默认工作区'], + ['en', 'Default workspace', 'Default workspace'], + ['fr', 'default-workspace', 'Default workspace'], + ])('prepares and selects the default Workspace after both startup baselines (%s)', async (language, directoryName, title) => { + const b = bench({ language, configureWorkspaces: (workspaces) => { + workspaces.initializeDefault.mockImplementation(async () => { + const item = workspace('default') + workspaces.list.set(workspaceState([item])) + return item + }) + } }) + expect(b.workspaces.initializeDefault).not.toHaveBeenCalled() + b.sessions.list.set(sessionState()) + expect(b.workspaces.initializeDefault).not.toHaveBeenCalled() + b.workspaces.list.set(workspaceState()) + await vi.waitFor(() => { + expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('created-default'), { source: 'mainView' }) }) - await expect(b.uiWorkspace.openDefaultWorkspace({ directoryName: '默认工作区', title: '默认工作区' }, beforeOpen, new AbortController().signal)) - .resolves.toBe(sid('created-default')) - expect(b.workspaces.initializeDefault).toHaveBeenCalledWith({ directoryName: '默认工作区', title: '默认工作区' }, expect.any(AbortSignal)) + expect(b.workspaces.initializeDefault).toHaveBeenCalledExactlyOnceWith({ directoryName, title }, expect.any(AbortSignal)) expect(b.sessions.create).toHaveBeenCalledWith({ workspaceId: wid('default') }) - expect(beforeOpen).toHaveBeenCalledWith(sid('created-default')) + expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(false) }) - it('does not create a Session when default preparation fails or is superseded', async () => { + it('leaves an ineligible empty installation without a Session or failure dialog', async () => { const b = bench({ workspaces: workspaceState(), sessions: sessionState() }) - b.workspaces.initializeDefault.mockRejectedValueOnce(new Error('denied')) - await expect(b.uiWorkspace.openDefaultWorkspace({ directoryName: 'Default workspace', title: 'Default workspace' }, vi.fn(), new AbortController().signal)).rejects.toThrow('denied') + await setImmediate() + b.workspaces.list.set(workspaceState()) + b.sessions.list.set(sessionState()) + await setImmediate() + expect(b.workspaces.initializeDefault).toHaveBeenCalledOnce() expect(b.sessions.create).not.toHaveBeenCalled() + expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(false) + }) + + it('requires explicit selection when the startup Session list contains history', async () => { + const b = bench({ workspaces: workspaceState(), sessions: sessionState([summary('history')]) }) + await setImmediate() + expect(b.workspaces.initializeDefault).not.toHaveBeenCalled() + expect(b.sessions.create).not.toHaveBeenCalled() + }) + + it('publishes a startup directory failure once without creating a Session', async () => { + const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => { + workspaces.initializeDefault.mockRejectedValueOnce(new Error('denied')) + } }) + await vi.waitFor(() => { expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(true) }) + b.uiWorkspace.defaultFailure.set(false) + b.workspaces.list.set(workspaceState()) + await setImmediate() + expect(b.workspaces.initializeDefault).toHaveBeenCalledOnce() + expect(b.sessions.create).not.toHaveBeenCalled() + expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(false) + }) + + it.each(['session', 'panel', 'disposal'] as const)('cancels startup directory preparation after %s navigation', async (kind) => { const pending = Promise.withResolvers() - b.workspaces.initializeDefault.mockReturnValueOnce(pending.promise) - const beforeOpen = vi.fn() - const opening = b.uiWorkspace.openDefaultWorkspace({ directoryName: 'Default workspace', title: 'Default workspace' }, beforeOpen, new AbortController().signal) - b.uiWorkspace.openSession(sid('manual')) + const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => { + workspaces.initializeDefault.mockReturnValueOnce(pending.promise) + } }) + if (kind === 'session') b.uiWorkspace.openSession(sid('manual')) + else if (kind === 'panel') b.layout.selectPanel('other-panel' as MainPanelId) + else await b.ctx.fiber.dispose() + expect(b.workspaces.initializeDefault.mock.calls[0]![1]?.aborted).toBe(true) pending.resolve(workspace('default')) - await expect(opening).resolves.toBeUndefined() + await setImmediate() expect(b.sessions.create).not.toHaveBeenCalled() - expect(beforeOpen).not.toHaveBeenCalled() + expect(b.sessions.retain.mock.calls.map(args => args[0])).toEqual(kind === 'session' ? [sid('manual')] : []) + expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(false) }) - it('retains the prepared Workspace if creating its Session fails', async () => { - const b = bench({ workspaces: workspaceState(), sessions: sessionState() }) - b.sessions.create.mockRejectedValueOnce(new Error('session failed')) - await expect(b.uiWorkspace.openDefaultWorkspace({ directoryName: 'Default workspace', title: 'Default workspace' }, vi.fn(), new AbortController().signal)).rejects.toThrow('session failed') - expect(b.workspaces.list.getSnapshot().items).toEqual([workspace('default')]) + it('retains a prepared Workspace when its Session fails and suppresses a superseded failure', async () => { + for (const superseded of [false, true]) { + const created = Promise.withResolvers() + const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => { + workspaces.initializeDefault.mockImplementationOnce(async () => { + const item = workspace('default') + workspaces.list.set(workspaceState([item])) + return item + }) + }, configureSessions: (sessions) => { sessions.create.mockReturnValueOnce(created.promise) } }) + await vi.waitFor(() => { expect(b.sessions.create).toHaveBeenCalledOnce() }) + if (superseded) b.layout.selectPanel('other-panel' as MainPanelId) + created.reject(new Error('session failed')) + await setImmediate() + expect(b.workspaces.list.getSnapshot().items).toEqual([workspace('default')]) + expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(!superseded) + expect(b.sessions.retain).not.toHaveBeenCalled() + } }) it('retains an explicit main target before revealing its Conversation', () => { diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index b89f2f3ada..37f5d7ec0e 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -3251,10 +3251,10 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'the Workspace and whether this call created it.', }, { - signature: '@Remote(\'initializeDefault\') async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise', - description: 'Initialize or reuse the default Workspace before the first user message.', + signature: '@Remote(\'initializeDefault\') async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise', + description: 'Initialize or reuse the default Workspace during first-use startup.', parameters: [{ name: 'request', description: 'initial directory name and title; never rename an existing default.' }, { name: 'signal', description: 'caller lifetime; cancels native directory lookup.' }], - returns: 'the durable Workspace without creating a Session or sending a message.', + returns: 'the durable Workspace, or undefined when first-use initialization is ineligible; creates no Session or message.', }, { signature: '@Remote(\'rename\') rename(request: WorkspaceRenameRequest): Promise', diff --git a/packages/test-support/client-runtime/src/workspaces.ts b/packages/test-support/client-runtime/src/workspaces.ts index 2c6b788fa3..63c1ec78d9 100644 --- a/packages/test-support/client-runtime/src/workspaces.ts +++ b/packages/test-support/client-runtime/src/workspaces.ts @@ -81,16 +81,15 @@ export class TestWorkspaces implements IWorkspaces { } /** - * Initialize the default Workspace through an explicitly installed test stub. + * Initialize the default Workspace through a test stub; defaults to an ineligible first use. * @param request - initial directory name and title. * @param signal - caller lifetime. - * @returns the stubbed Workspace. + * @returns the stubbed Workspace, or undefined when initialization is ineligible. */ - async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise { + async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise { this.calls.push({ method: 'initializeDefault', args: [request, signal] }) const stub = this.stubs.get('initializeDefault') - if (stub === undefined) throw new Error('initializeDefault requires a Workspace fixture') - return await (stub(request, signal) as Promise) + return await (stub?.(request, signal) as Promise | undefined) } /** diff --git a/packages/test-support/client-runtime/tests/runtime.client.spec.tsx b/packages/test-support/client-runtime/tests/runtime.client.spec.tsx index aeff2554d1..ca9523edbe 100644 --- a/packages/test-support/client-runtime/tests/runtime.client.spec.tsx +++ b/packages/test-support/client-runtime/tests/runtime.client.spec.tsx @@ -557,12 +557,12 @@ describe('workspaces', () => { expect(view.container.textContent).toContain('ws:pending') await runtime.dispose() }) - it('requires an explicit default Workspace fixture and forwards its request and lifetime', async () => { + it('skips default initialization without a fixture and forwards a configured request and lifetime', async () => { const runtime = await SlotTestRuntime.create() try { const request = { directoryName: 'default-workspace', title: 'Default workspace' } const signal = new AbortController().signal - await expect(runtime.workspaces.initializeDefault(request, signal)).rejects.toThrow('requires a Workspace fixture') + await expect(runtime.workspaces.initializeDefault(request, signal)).resolves.toBeUndefined() const workspace = { workspaceId: 'default' as WorkspaceId, title: request.title, path: '/default', sessionIds: [], createdAt: '2026-09-20T00:00:00Z', updatedAt: '2026-09-20T00:00:00Z', diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 1f19959e7e..adababb1a4 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -246,7 +246,6 @@ export const EVENT_SCOPE_PAGE: Record = { export const EVENT_WALK_EXEMPTIONS: Record = { 'command/executed': 'client-face local command acknowledgment — packages/client/ui-commands/README.md owns the API', 'connection/reset': 'client-face transport signal — packages/api/session-controller/README.md owns the API', - 'conversation/prepare-first-send': 'client-face first-use draft preparation — packages/client/ui-conversation/README.md owns the API', 'locale/change': 'client-face locale switch signal — packages/client/locale/README.md owns the API', 'slash/input-begin-command': 'client-face slash-input protocol — packages/client/ui-input-trigger/README.md owns the API', 'slash/input-consume-token': 'client-face slash-input protocol — packages/client/ui-input-trigger/README.md owns the API', From 3a7f8f9657c1516aab510fbadecbc3e10152185d Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 17:20:44 +0800 Subject: [PATCH 09/27] test(web): restore ordinary workspace picker readiness --- apps/web/tests/preview-boot.e2e.ts | 4 ++-- apps/web/tests/sessionless-header.e2e.ts | 2 +- apps/web/tests/startup-rpc-budget.e2e.ts | 2 +- apps/web/tests/support.ts | 23 ++++++++++++++++------- 4 files changed, 20 insertions(+), 11 deletions(-) diff --git a/apps/web/tests/preview-boot.e2e.ts b/apps/web/tests/preview-boot.e2e.ts index 4797a6e4bf..bde54fe69e 100644 --- a/apps/web/tests/preview-boot.e2e.ts +++ b/apps/web/tests/preview-boot.e2e.ts @@ -297,7 +297,7 @@ async function bootPreview(origin: string, browser: Browser): Promise { expect(await page.getByText('Empty environment', { exact: true }).count()).toBe(1) expect(await page.getByText('WebFS directory', { exact: true }).count()).toBe(1) expect(await page.locator('input[name="preview-source"][value="webfs"]').isDisabled()).toBe(true) - expect(await page.getByRole('button', { name: 'Choose workspace' }).count()).toBe(0) + expect(await page.getByRole('textbox', { name: 'Choose workspace' }).count()).toBe(0) await compareOrRefreshGolden( SOURCE_CHOOSER_EXPECTED, await captureStableAria(page, '[data-preview-source-card]', '/__preview_no_workspace__'), @@ -471,7 +471,7 @@ async function bootEmptyPreview(origin: string, browser: Browser): Promise ) expect(bootLine).toContain(`image lowering=${WRAPPER_CONTRACT}`) expect(bootLine).toContain('data overlays=0') - await page.getByRole('button', { name: 'Choose workspace' }).waitFor({ timeout: HERO_TIMEOUT_MS }) + await page.getByRole('textbox', { name: 'Choose workspace' }).waitFor({ timeout: HERO_TIMEOUT_MS }) const sessionCount = await page.evaluate(async () => { const transport = (globalThis as typeof globalThis & { __DSH_TRANSPORT__?: { fetch(input: string, init: RequestInit): Promise } diff --git a/apps/web/tests/sessionless-header.e2e.ts b/apps/web/tests/sessionless-header.e2e.ts index 1de5dfe14f..b2c1a85fb0 100644 --- a/apps/web/tests/sessionless-header.e2e.ts +++ b/apps/web/tests/sessionless-header.e2e.ts @@ -30,7 +30,7 @@ describe('navigation without a selected Session', () => { } const tripwire = watchConsole(page) await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) - await page.getByRole('button', { name: 'Choose workspace', exact: true }).waitFor() + await page.getByRole('textbox', { name: 'Choose workspace', exact: true }).waitFor() const sessionHeader = page.locator('[data-slot="conversation.session.header"]') expect(await sessionHeader.count()).toBe(0) const header = page.locator('[data-slot="conversation.header"] > header') diff --git a/apps/web/tests/startup-rpc-budget.e2e.ts b/apps/web/tests/startup-rpc-budget.e2e.ts index d8c89afcca..f6655ffbf3 100644 --- a/apps/web/tests/startup-rpc-budget.e2e.ts +++ b/apps/web/tests/startup-rpc-budget.e2e.ts @@ -36,7 +36,7 @@ describe('startup RPC budget', () => { await page.goto(scaffold.authenticatedUrl) // Boot settles when the workspace picker is interactive; the trailing wait // absorbs the first-connection reset wave the budget must include. - await page.getByRole('button', { name: 'Choose workspace' }).waitFor({ timeout: 30_000 }) + await page.getByRole('textbox', { name: 'Choose workspace' }).waitFor({ timeout: 30_000 }) await page.waitForTimeout(3000) const describeCount = calls.filter(method => method === 'settings/describe').length expect(describeCount, `startup /api calls:\n${calls.join('\n')}`).toBe(DESCRIBE_BUDGET) diff --git a/apps/web/tests/support.ts b/apps/web/tests/support.ts index 082f5019ae..fc29e7f913 100644 --- a/apps/web/tests/support.ts +++ b/apps/web/tests/support.ts @@ -105,16 +105,25 @@ export function probeFreePort(): Promise { } /** - * Select a staged directory through the hero's composed Workspace picker. - * The default name keeps the Session cwd at /workspace for scenarios - * that require a specific directory instead of automatic first-use preparation. + * Drive the hero's workspace picker through the composed directory dialog + * until the live composer unlocks. A fresh world has no Workspace, so the boot + * lands in the Workspace-trigger view state (startup auto-selection has nothing to + * select); every scenario that types into the composer must connect one + * first. With nothing to list, activating the composer surface raises the dialog directly — + * adding a workspace is the picker's only entry. The directory is staged here + * and adopted through the path editor, which is idempotent across the repeated + * connects a scenario may make; creating a folder from inside the dialog (the + * product's other half of the same route) is covered by + * workspace-management.e2e.ts. The default name 'workspace' keeps the session + * header cwd at /workspace, the materialization proof several scenarios + * assert. * @param page - the page under test. * @param root - host directory the workspace folder is staged in (the scaffold's `workspaceCwd`). * @param name - folder name staged and adopted as the workspace. */ export async function connectFreshWorkspace(page: Page, root: string, name = 'workspace'): Promise { mkdirSync(join(root, name), { recursive: true }) - await page.getByRole('button', { name: 'Choose workspace', exact: true }).click() + await page.getByRole('textbox', { name: 'Choose workspace' }).click() const dialog = page.getByRole('dialog', { name: 'Select Workspace Directory' }) await dialog.waitFor({ timeout: 10_000 }) await dialog.getByRole('button', { name: 'Edit path' }).click() @@ -122,7 +131,8 @@ export async function connectFreshWorkspace(page: Page, root: string, name = 'wo await pathInput.fill(join(root, name)) await pathInput.press('Enter') await dialog.getByRole('button', { name: 'Open', exact: true }).click() - await page.locator('[data-slot="conversation.session.header"]').waitFor({ state: 'attached', timeout: 15_000 }) + // The pick connected the workspace: the blank session's live composer + // replaces the locked placeholder and enables. await page.locator('[data-composer-input][contenteditable="true"][data-placeholder="Describe what you want to build, / commands, @ files or sessions"]') .waitFor({ timeout: 15_000 }) } @@ -138,7 +148,7 @@ export async function connectFreshWorkspace(page: Page, root: string, name = 'wo */ export async function connectFreshWorkspaceZh(page: Page, root: string, name = 'workspace'): Promise { mkdirSync(join(root, name), { recursive: true }) - await page.getByRole('button', { name: '选择工作区', exact: true }).click() + await page.getByRole('textbox', { name: '选择工作区' }).click() const dialog = page.getByRole('dialog', { name: '选择工作区目录' }) await dialog.waitFor({ timeout: 10_000 }) await dialog.getByRole('button', { name: '编辑路径' }).click() @@ -146,7 +156,6 @@ export async function connectFreshWorkspaceZh(page: Page, root: string, name = ' await pathInput.fill(join(root, name)) await pathInput.press('Enter') await dialog.getByRole('button', { name: '打开', exact: true }).click() - await page.locator('[data-slot="conversation.session.header"]').waitFor({ state: 'attached', timeout: 15_000 }) await page.locator('[data-composer-input][contenteditable="true"][data-placeholder="描述你想要构建的内容, / 调用指令, @ 文件或对话"]') .waitFor({ timeout: 15_000 }) } From 2cd03c97582f84924ceafab9b0c8809d7606979d Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 17:20:54 +0800 Subject: [PATCH 10/27] refactor(workspace): omit unchanged registry state fields --- packages/workspace/workspace/src/index.ts | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/packages/workspace/workspace/src/index.ts b/packages/workspace/workspace/src/index.ts index d0f3d3b8a5..e2f67d948a 100644 --- a/packages/workspace/workspace/src/index.ts +++ b/packages/workspace/workspace/src/index.ts @@ -459,8 +459,6 @@ export class WorkspaceRegistry extends Service { initialized: true, ...(firstUse ? { defaultWorkspaceId: id } : {}), workspaceIds: [id, ...state.workspaceIds], - archivedSessionIds: state.archivedSessionIds, - pinnedSessionIds: state.pinnedSessionIds, }) } catch (error) { this.entities.delete(id) @@ -494,8 +492,6 @@ export class WorkspaceRegistry extends Service { pendingMutation: undefined, initialized: true, workspaceIds: state.workspaceIds.filter(workspaceId => workspaceId !== id), - archivedSessionIds: state.archivedSessionIds, - pinnedSessionIds: state.pinnedSessionIds, } await this.setState({ ...nextState, @@ -549,14 +545,7 @@ export class WorkspaceRegistry extends Service { ) } await this.requireTable().delete(pending.workspaceId) - await this.setState({ - ...state, - pendingMutation: undefined, - initialized: state.initialized, - workspaceIds: state.workspaceIds, - archivedSessionIds: state.archivedSessionIds, - pinnedSessionIds: state.pinnedSessionIds, - }) + await this.setState({ ...state, pendingMutation: undefined }) } private async bootstrap(headers: readonly SessionHeader[]): Promise { From 78d6f7bc1fafe4d60fd69fab03c043d4f4a90d66 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 17:48:46 +0800 Subject: [PATCH 11/27] test(client): mock default workspace initialization during boot --- .../client-runtime/src/assembly/remote-default-responses.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts b/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts index c54130bca5..485882f05f 100644 --- a/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts +++ b/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts @@ -13,6 +13,8 @@ export const remoteDefaultResponses: RemoteTable = { unary: { // api-session-controller `sessions.handleConnected()` on `connection/reset`. 'session/list': ok({ items: [] }), + // ui-workspace startup with no entries; first-use initialization is ineligible. + 'workspace/initializeDefault': ok(undefined), // ui-settings `mirror.ensure()` at apply and again on `connection/reset`. 'settings/describe': ok({ writable: true, hasDocument: false, namespaces: [] }), // ui-model-selection `ModelDirectoryResolver` constructor. From 5294b15b3102bfd4899b13fa3fb1a4ac69419c5a Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 17:48:58 +0800 Subject: [PATCH 12/27] docs(workspace): separate constructor parameter tags --- packages/api/workspace-controller/src/index.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/api/workspace-controller/src/index.ts b/packages/api/workspace-controller/src/index.ts index 7a63e5b699..928f52f883 100644 --- a/packages/api/workspace-controller/src/index.ts +++ b/packages/api/workspace-controller/src/index.ts @@ -61,7 +61,10 @@ export class WorkspaceController extends TypertRemoteService { private readonly commands: WorkspaceCommands private readonly feed: WorkspaceFeed - /** @param ctx - Host context containing the Workspace registry. @param config - first-use directory policy. */ + /** + * @param ctx - Host context containing the Workspace registry. + * @param config - first-use directory policy. + */ constructor(ctx: Context, config: Config = {}) { super(ctx, 'workspaceController', { namespace: 'workspace' }) this.config = WorkspaceController.Config(config) From 5ec3353af2be73c6773ae3ce917d547f0ea5cd3a Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 20:42:50 +0800 Subject: [PATCH 13/27] refactor(workspace): reuse toast for default initialization failures --- apps/web/tests/default-workspace.e2e.ts | 14 ++-- .../default-workspace/failure.expected.md | 7 +- packages/client/ui-workspace/README.i18n.yaml | 4 +- packages/client/ui-workspace/README.md | 2 +- packages/client/ui-workspace/README.zh.md | 2 +- .../src/client/WorkspacePicker.tsx | 48 ++++--------- .../ui-workspace/src/client/contract/slots.ts | 9 +-- .../client/ui-workspace/src/client/index.ts | 13 ++-- .../client/ui-workspace/src/client/locales.ts | 8 +-- .../ui-workspace/src/client/navigation.ts | 20 +++--- .../client/session-actions/RowActionToast.tsx | 13 ++-- .../ui-workspace/tests/apply.client.spec.ts | 20 +++++- .../tests/session-actions.client.spec.tsx | 1 + .../tests/workspace-picker.client.spec.tsx | 35 +--------- .../tests/workspaces-service.client.spec.ts | 69 ++++++++++++------- 15 files changed, 114 insertions(+), 151 deletions(-) diff --git a/apps/web/tests/default-workspace.e2e.ts b/apps/web/tests/default-workspace.e2e.ts index d3b6db624d..d27f430fd3 100644 --- a/apps/web/tests/default-workspace.e2e.ts +++ b/apps/web/tests/default-workspace.e2e.ts @@ -81,16 +81,14 @@ describe.skipIf(MODE === 'record')('web e2e: default Workspace', () => { try { await page.goto(scaffold.authenticatedUrl) const input = page.locator('[data-composer-input][contenteditable="true"]').first() - const modal = page.getByRole('dialog', { name: '无法创建默认工作区' }) - await modal.waitFor() + const notice = page.getByRole('alert').filter({ hasText: '无法创建默认工作区' }) + await notice.waitFor() expect(scaffold.ctx.workspaceRegistry.list()).toEqual([]) expect(scaffold.ctx.sessions.list()).toEqual([]) - await compareOrRefreshGolden(FAILURE_EXPECTED, await modal.ariaSnapshot(), MODE) - await modal.getByRole('button', { name: '取消', exact: true }).click() + await compareOrRefreshGolden(FAILURE_EXPECTED, await notice.ariaSnapshot(), MODE) + expect(await page.getByRole('dialog').count()).toBe(0) expect(await input.count()).toBe(0) - await page.reload() - await modal.waitFor() - await modal.getByRole('button', { name: '选择文件夹', exact: true }).click() + await page.getByRole('button', { name: '选择工作区', exact: true }).click() const picker = page.getByRole('dialog', { name: '选择工作区目录' }) await picker.waitFor() await picker.getByRole('button', { name: '编辑路径', exact: true }).click() @@ -126,7 +124,7 @@ describe.skipIf(MODE === 'record')('web e2e: default Workspace', () => { await page.goto(scaffold.authenticatedUrl) expect((await attempted).ok()).toBe(true) await page.getByRole('button', { name: 'Choose workspace', exact: true }).waitFor() - expect(await page.getByRole('dialog', { name: 'Unable to create default workspace' }).count()).toBe(0) + expect(await page.getByRole('alert').filter({ hasText: 'Unable to create default workspace' }).count()).toBe(0) expect(await page.locator('[data-composer-input][contenteditable="true"]').count()).toBe(0) expect(scaffold.ctx.workspaceRegistry.list()).toEqual([]) expect(scaffold.ctx.sessions.list()).toEqual([]) diff --git a/apps/web/tests/expected/default-workspace/failure.expected.md b/apps/web/tests/expected/default-workspace/failure.expected.md index 6944d1cf14..c9624749f0 100644 --- a/apps/web/tests/expected/default-workspace/failure.expected.md +++ b/apps/web/tests/expected/default-workspace/failure.expected.md @@ -1,6 +1 @@ -- dialog "无法创建默认工作区": - - heading "无法创建默认工作区" [level=2] - - button "关闭" - - text: 请选择一个文件夹后重试 - - button "取消" - - button "选择文件夹" +- alert: 无法创建默认工作区,请通过“选择工作区”选择文件夹 diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index 4af8adc8d4..2f176f2329 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-workspace/README.md -README.md: 768c66503af70d0b587b25c09aa8412b0a647439 -README.zh.md: 25df6f8e6a2ec0a001d784c7bde18e454e9d706f +README.md: bf67f12f15f634a29dc05744c079255723ae2a62 +README.zh.md: e57700d983b31872383fc4b26f9b5b080d66ba6c diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index 768c66503a..bf67f12f15 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -69,7 +69,7 @@ The value is intentionally best effort for cold Sessions. An identity-matching u New Session tries to acquire the first eligible blank in catalog order; startup restoration tries the saved blank. If that writer is held, navigation creates a new Session without trying other blanks. Other acquisition failures abort the request and are currently reported only to the console. Released blanks retain their slash-command state when reused. Later navigation cancels a pending startup selection. -Once both Workspace and Session startup baselines are ready, an empty installation calls `workspaces.initializeDefault` and creates or reuses its blank Session. The composer becomes editable when that Session is selected; no message is submitted automatically. Later navigation or owner disposal prevents startup from selecting its result. Ineligible first use leaves the folder picker available without an error. Preparation failure offers Cancel or Choose folder through the existing picker, and is not retried until the next startup. A successfully registered Workspace remains available when Session creation or later submission fails. +Once both Workspace and Session startup baselines are ready, an empty installation calls `workspaces.initializeDefault` and creates or reuses its blank Session. The composer becomes editable when that Session is selected; no message is submitted automatically. Later navigation or owner disposal prevents startup from selecting its result. Ineligible first use leaves the folder picker available without an error. Default Workspace creation failure shows a transient notice directing the user to Choose workspace, and is not retried until the next startup. Session creation failures use the ordinary restoration error handling. The registered Workspace remains available if Session creation or later submission fails. The Client chooses the initial directory name and title from its language at startup: Chinese uses `默认工作区`, English uses `Default workspace`, and other languages use directory `default-workspace` with title `Default workspace`. The request retains those names during initialization. A successfully initialized Workspace keeps its directory and title across language changes. diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index 25df6f8e6a..e57700d983 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -69,7 +69,7 @@ Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示** 新建会话尝试获取列表中第一个符合条件的空白会话;启动恢复尝试已保存的空白会话。若该写锁被占用,导航直接新建 Session,不再尝试其他空白会话。其他获取错误会中止请求,目前只报告到控制台。已释放的空白会话被复用时保留 slash 命令状态。后续导航会取消尚未完成的启动选择。 -Workspace 和 Session 的启动基线均就绪后,空安装环境调用 `workspaces.initializeDefault`,创建或复用其空白 Session。选中该 Session 后输入框才可编辑,不会自动提交消息。后续导航或所属上下文销毁会阻止启动流程选中其结果。不符合首次使用条件时仍可选择文件夹,不显示错误。准备失败时通过现有选择器提供取消或选择文件夹操作,直到下次启动才重试。登记成功的工作区在 Session 创建或后续提交失败时仍然保留。 +Workspace 和 Session 的启动基线均就绪后,空安装环境调用 `workspaces.initializeDefault`,创建或复用其空白 Session。选中该 Session 后输入框才可编辑,不会自动提交消息。后续导航或所属上下文销毁会阻止启动流程选中其结果。不符合首次使用条件时仍可选择文件夹,不显示错误。默认工作区创建失败时显示短暂提示,引导用户通过“选择工作区”选择文件夹,直到下次启动才重试。Session 创建失败沿用普通的恢复错误处理。登记成功的工作区在 Session 创建或后续提交失败时仍然保留。 Client 在启动时按其语言选择初始目录名和标题:中文使用 `默认工作区`,英文使用 `Default workspace`,其他语言使用目录 `default-workspace` 和标题 `Default workspace`。初始化过程中保留请求中的名称。成功初始化的工作区在切换语言后保留原目录和标题。 diff --git a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx index 42e177afce..b74e3689dc 100644 --- a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx +++ b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx @@ -231,45 +231,21 @@ export function WorkspacePicker({ onClose, createWorkspace, useDirectoryFlow, - useDefaultFailure, - dismissDefaultFailure, renderSlot, t, }: WorkspacePickerProps) { - const failed = useDefaultFailure(value => value) - const flowAvailable = useDirectoryFlow(value => value) - const [recovering, setRecovering] = useState(false) return ( - <> - renderSlot('conversation.hero.workspace.directoryFlow', owner)} - selectedId={selectedId} - onPick={onPick} - onClose={() => { setRecovering(false); onClose() }} - /> - - - - - )} - > - {t('defaultWorkspace.retry')} - - + renderSlot('conversation.hero.workspace.directoryFlow', owner)} + selectedId={selectedId} + onPick={onPick} + onClose={onClose} + /> ) } diff --git a/packages/client/ui-workspace/src/client/contract/slots.ts b/packages/client/ui-workspace/src/client/contract/slots.ts index b878e24986..36ab1850d4 100644 --- a/packages/client/ui-workspace/src/client/contract/slots.ts +++ b/packages/client/ui-workspace/src/client/contract/slots.ts @@ -238,12 +238,13 @@ export type SessionRowActionProps = & PropsLocale<'workspace'> & InjectFace -/** One transient notice a row action raises; the overlay toast entry renders it. */ +/** One transient Workspace notice rendered by the overlay toast entry. */ export type RowToast = | { kind: 'archived'; sessionId: SessionId } | { kind: 'pinFailed' } | { kind: 'unpinFailed' } | { kind: 'archivedNotOpenable' } + | { kind: 'defaultWorkspaceFailed' } /** The notice on display; `seq` keys remounts so a repeated notice restarts its hold. */ export type RowToastState = RowToast & { seq: number } @@ -364,12 +365,6 @@ export type WorkspaceBrowserProps = * supplies the implicit index signature required by the registry. */ export type WorkspacePickerInjected = DirectoryPickingInjected & { - /** Dismiss the startup failure before choosing a directory manually. */ - dismissDefaultFailure: () => void - hooks: { - /** Whether first-use startup failed to prepare a Workspace and Session. */ - defaultFailure: HostObservable - } /** Adopt a picked host directory as a real Workspace before targeting a Session. */ createWorkspace: (input: { path: string }) => Promise } diff --git a/packages/client/ui-workspace/src/client/index.ts b/packages/client/ui-workspace/src/client/index.ts index 8d96c65d77..7c821033d6 100644 --- a/packages/client/ui-workspace/src/client/index.ts +++ b/packages/client/ui-workspace/src/client/index.ts @@ -103,8 +103,13 @@ export function apply(ctx: Context): void { const viewHandle = createWorkspaceViewStore() const viewInstance = viewHandle.create() const viewStore: typeof viewHandle = { ...viewHandle, create: () => viewInstance } + const rowToast = createSnapshotStore(null) + let toastSeq = 0 + const notify = (toast: RowToast): void => { rowToast.set({ ...toast, seq: ++toastSeq }) } const uiWorkspace = new UiWorkspaceService( - ctx, ctx.remote.directoryPicker, workspaces, sessions, viewInstance.actions) + ctx, ctx.remote.directoryPicker, workspaces, sessions, viewInstance.actions, + () => { notify({ kind: 'defaultWorkspaceFailed' }) }, + ) ctx.slots.provideRoot({ hooks: { workspaces: workspaces.list } }) ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-workspace: dictionaries') @@ -137,9 +142,6 @@ export function apply(ctx: Context): void { // writes through its own injected callback and the surface reads through // its bound hook. const renameRequest = createSnapshotStore(null) - const rowToast = createSnapshotStore(null) - let toastSeq = 0 - const notify = (toast: RowToast): void => { rowToast.set({ ...toast, seq: ++toastSeq }) } const requestSessionRename = (sessionId: SessionId, currentTitle: string): void => { renameRequest.set({ sessionId, currentTitle }) } @@ -219,8 +221,7 @@ export function apply(ctx: Context): void { }) const pickerInjected = (): WorkspacePickerInjected => ({ createWorkspace: input => workspaces.create(input), - dismissDefaultFailure: () => { uiWorkspace.defaultFailure.set(false) }, - hooks: { directoryFlow: pickerFlowSource, defaultFailure: uiWorkspace.defaultFailure }, + hooks: { directoryFlow: pickerFlowSource }, }) // Each registration declares its owned children in the same call; slot // injection follows both the owner and declaration HMR lifetimes. diff --git a/packages/client/ui-workspace/src/client/locales.ts b/packages/client/ui-workspace/src/client/locales.ts index d926ce987f..3ecc46741f 100644 --- a/packages/client/ui-workspace/src/client/locales.ts +++ b/packages/client/ui-workspace/src/client/locales.ts @@ -6,10 +6,8 @@ /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { - 'defaultWorkspace.failed': '无法创建默认工作区', + 'defaultWorkspace.failed': '无法创建默认工作区,请通过“选择工作区”选择文件夹', 'defaultWorkspace.title': '默认工作区', - 'defaultWorkspace.retry': '请选择一个文件夹后重试', - 'defaultWorkspace.choose': '选择文件夹', 'group.ungrouped': '未分组', 'session.new': '新会话', 'section.workspaces': '工作区', @@ -103,10 +101,8 @@ export type WorkspaceKey = keyof typeof zh /** English dictionary, checked complete against the zh key set. */ export const en = { - 'defaultWorkspace.failed': 'Unable to create default workspace', + 'defaultWorkspace.failed': 'Unable to create default workspace. Use Choose workspace to select a folder.', 'defaultWorkspace.title': 'Default workspace', - 'defaultWorkspace.retry': 'Please choose a folder and try again', - 'defaultWorkspace.choose': 'Choose folder', 'group.ungrouped': 'Ungrouped', 'session.new': 'New Session', 'section.workspaces': 'Workspaces', diff --git a/packages/client/ui-workspace/src/client/navigation.ts b/packages/client/ui-workspace/src/client/navigation.ts index b21cf06f15..13c12651fd 100644 --- a/packages/client/ui-workspace/src/client/navigation.ts +++ b/packages/client/ui-workspace/src/client/navigation.ts @@ -120,8 +120,6 @@ export class DirectoryBrowseError extends Error { /** Implements Workspace archive and directory UI operations. */ class UiWorkspaceService extends Service implements UiWorkspace { - /** Startup failure awaiting dismissal or explicit directory selection. */ - readonly defaultFailure = createSnapshotStore(false) private readonly connecting = new Map>() private readonly lifetime = new AbortController() private readonly selection = createSnapshotStore( @@ -135,6 +133,7 @@ class UiWorkspaceService extends Service implements UiWorkspace { * @param workspaces - pure Workspace Controller. * @param sessions - pure Session Controller. * @param view - the browser's viewing-store write set (one instance shared with its registration). + * @param notifyDefaultFailure - show the startup creation failure through the Workspace notice channel. */ constructor( ctx: Context, @@ -142,6 +141,7 @@ class UiWorkspaceService extends Service implements UiWorkspace { private readonly workspaces: IWorkspaces, private readonly sessions: ISessions, private readonly view: Pick, + private readonly notifyDefaultFailure: () => void, ) { super(ctx, 'uiWorkspace') ctx.effect(() => { @@ -324,28 +324,28 @@ class UiWorkspaceService extends Service implements UiWorkspace { && !workspaces.archivedSessionIds.includes(summary.id)) { sessionId = await this.reuseBlank(workspace.workspaceId, summary.id) } - const target = workspace?.workspaceId ?? recentWorkspace(workspaces.items, sessions.byId) - if (sessionId === undefined && target !== undefined) sessionId = await this.connectWorkspace(target) + let target = workspace?.workspaceId ?? recentWorkspace(workspaces.items, sessions.byId) if (target === undefined && workspaces.items.length === 0 && sessions.ids.length === 0) { - sessionId = await this.initializeDefaultWorkspace(navigation) + const prepared = await this.initializeDefaultWorkspace(navigation) + if (navigation.aborted) return + target = prepared?.workspaceId } + if (sessionId === undefined && target !== undefined) sessionId = await this.connectWorkspace(target) if (sessionId !== undefined && !navigation.aborted) { this.replaceMain(sessionId, navigation, 'preserve') } } - private async initializeDefaultWorkspace(signal: AbortSignal): Promise { + private async initializeDefaultWorkspace(signal: AbortSignal): Promise { const language = this.ctx.locale.getSnapshot().active.toLowerCase().split('-')[0] const title = (language === 'zh' ? zh : en)['defaultWorkspace.title'] try { - const workspace = await this.workspaces.initializeDefault({ + return await this.workspaces.initializeDefault({ directoryName: language === 'zh' || language === 'en' ? title : 'default-workspace', title, }, signal) - if (workspace === undefined || signal.aborted) return undefined - return await this.connectWorkspace(workspace.workspaceId) } catch (_error: unknown) { - if (!signal.aborted) this.defaultFailure.set(true) + if (!signal.aborted) this.notifyDefaultFailure() return undefined } } diff --git a/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx b/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx index f000fc4b4a..c5a3caccc6 100644 --- a/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx +++ b/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx @@ -1,8 +1,6 @@ /** - * The `shell.overlay` entry that shows the row actions' notices: the archived - * notice with its undo and "show archived" actions, pin failures, and the - * browser's "archived rows cannot be opened" notice. One notice at a time; - * a parent rerender does not extend its hold. + * The `shell.overlay` entry for Workspace and Session notices. + * One notice is visible at a time; a parent rerender does not extend its hold. */ import { IconWarningOutlineRegular, Toast } from '@deepseek-ai/dsh-client-ui-primitives' import type { RowToastProps } from '../contract/slots.ts' @@ -11,9 +9,9 @@ import type { RowToastProps } from '../contract/slots.ts' const ARCHIVED_TOAST_HOLD_MS = 6000 /** - * Render the row actions' current notice: the archived notice with its undo + * Render the current notice: the archived notice with its undo * and show-archived actions on a 6 s hold, or a plain warning for a failed - * pin or an archived row that was clicked. + * pin, an archived row that was clicked, or default Workspace creation. * @param props - the notice hook, its dismissal, the two archived-notice actions, and the locale seat. * @returns the notice on display, or null. */ @@ -38,7 +36,8 @@ export function RowActionToast({ useToast, dismissToast, undoArchive, showArchiv } const text = toast.kind === 'pinFailed' ? t('toast.pinFailed') - : toast.kind === 'unpinFailed' ? t('toast.unpinFailed') : t('toast.archivedNotOpenable') + : toast.kind === 'unpinFailed' ? t('toast.unpinFailed') + : toast.kind === 'defaultWorkspaceFailed' ? t('defaultWorkspace.failed') : t('toast.archivedNotOpenable') return ( () => {} const workspacesSubscribe = vi.fn(subscribe) + const initializeDefault = vi.fn(async (): Promise => undefined) ctx.provide('workspaces', { list: { getSnapshot: () => workspaceSnapshot, subscribe: workspacesSubscribe }, create, + initializeDefault, rename, delete: vi.fn(async () => undefined), insertBefore: vi.fn(async () => undefined), @@ -128,7 +130,7 @@ async function bench() { return { ctx, slots: ctx.get('slots') as SlotRegistry, locale, create, rename, retain, using, selectPanel, search, renameSession, binding, fork, pickDirectory, pinSession, unpinSession, - workspacesSubscribe, + workspacesSubscribe, initializeDefault, setWorkspaces: (snapshot: WorkspaceSnapshot): void => { workspaceSnapshot = snapshot }, setSessions: (snapshot: SessionListState): void => { sessionSnapshot = snapshot }, } @@ -182,6 +184,20 @@ describe('ui-workspace apply', () => { ]) }) + it('reports a default Workspace creation failure through the shared notice overlay', async () => { + const b = await bench() + onTestFinished(() => b.ctx.fiber.dispose()) + b.initializeDefault.mockRejectedValueOnce(new Error('denied')) + declare(b.slots, 'shell.overlay') + await b.ctx.plugin({ inject: [...inject], apply }).await() + const face = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected + await vi.waitFor(() => { + expect(face.hooks.toast.getSnapshot()).toMatchObject({ kind: 'defaultWorkspaceFailed' }) + }) + face.dismissToast() + expect(face.hooks.toast.getSnapshot()).toBeNull() + }) + it('registers browser and pickers for declarations arriving before or after apply', async () => { const before = await bench() declare(before.slots, 'sidebar.workspaces') diff --git a/packages/client/ui-workspace/tests/session-actions.client.spec.tsx b/packages/client/ui-workspace/tests/session-actions.client.spec.tsx index ce5cb47dda..c7e3b1150d 100644 --- a/packages/client/ui-workspace/tests/session-actions.client.spec.tsx +++ b/packages/client/ui-workspace/tests/session-actions.client.spec.tsx @@ -387,6 +387,7 @@ describe('RowActionToast', () => { ['pinFailed', '置顶失败,请稍后重试'], ['unpinFailed', '取消置顶失败,请稍后重试'], ['archivedNotOpenable', '已归档对话暂时无法查看,请取消归档后查看'], + ['defaultWorkspaceFailed', '无法创建默认工作区,请通过“选择工作区”选择文件夹'], ] as const)('shows the %s warning and takes it down when its hold ends', (kind, text) => { vi.useFakeTimers() try { diff --git a/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx b/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx index e72d523668..9ff0181207 100644 --- a/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx @@ -1,7 +1,6 @@ // @vitest-environment jsdom import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots' import { afterEach, describe, expect, it, vi } from 'vitest' -import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client' import type { @@ -89,19 +88,14 @@ function mount( items: readonly WorkspaceView[] = [workspace('alpha', 'Alpha')], createWorkspace = vi.fn(), occupancy = occupancySource(), - options: { defaultFailure?: boolean; open?: boolean } = {}, ) { - const failure = createSnapshotStore(options.defaultFailure ?? false) - const useDefaultFailure = bindSnapshotSelector(failure) - const dismissDefaultFailure = vi.fn(() => { failure.set(false) }) const onPick = vi.fn() const onClose = vi.fn() const anchorRef = anchor() const { probe, renderSlot } = flowProbe() const renderPicker = (nextItems: readonly WorkspaceView[]) => ( { view.rerender(renderPicker(nextItems)) }, } } @@ -226,7 +220,6 @@ describe('WorkspacePicker', () => { const { renderSlot } = flowProbe() render( undefined} @@ -245,7 +238,6 @@ describe('WorkspacePicker', () => { const { renderSlot } = flowProbe() render( undefined} @@ -329,26 +321,3 @@ describe('WorkspacePicker', () => { expect(screen.queryByRole('menuitem', { name: '添加工作区…' })).toBeNull() }) }) - -describe('default Workspace startup recovery', () => { - it('dismisses the failure without opening the directory flow', () => { - const b = mount([], vi.fn(), occupancySource(), { defaultFailure: true, open: false }) - expect(screen.getByRole('dialog', { name: '无法创建默认工作区' })).toBeTruthy() - expect(b.probe.owner?.open).toBe(false) - fireEvent.click(screen.getByRole('button', { name: '取消' })) - expect(b.dismissDefaultFailure).toHaveBeenCalledOnce() - expect(screen.queryByRole('dialog', { name: '无法创建默认工作区' })).toBeNull() - expect(b.probe.owner?.open).toBe(false) - }) - - it('opens the composed directory flow from the startup failure', async () => { - const create = vi.fn(async () => workspace('chosen')) - const b = mount([], create, occupancySource(), { defaultFailure: true, open: false }) - fireEvent.click(screen.getByRole('button', { name: '选择文件夹' })) - expect(b.dismissDefaultFailure).toHaveBeenCalledOnce() - expect(b.probe.owner?.open).toBe(true) - await act(async () => { b.probe.owner!.onPicked('/chosen') }) - expect(create).toHaveBeenCalledExactlyOnceWith({ path: '/chosen' }) - expect(b.onPick).toHaveBeenCalledExactlyOnceWith(wid('chosen')) - }) -}) diff --git a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts index 4f9cd973b8..8efdb0af95 100644 --- a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts +++ b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts @@ -294,14 +294,16 @@ function bench(options: BenchOptions = {}) { options.configureWorkspaces?.(workspaces) options.configureSessions?.(sessions) const view = createWorkspaceViewStore().create() + const notifyDefaultFailure = vi.fn() const uiWorkspace = new UiWorkspaceService( ctx, directoryPicker.remote, workspaces, sessions, view.actions, + notifyDefaultFailure, ) - return { ctx, directoryPicker, sessions, uiWorkspace, workspaces, layout, selectPanel, view } + return { ctx, directoryPicker, sessions, uiWorkspace, workspaces, layout, selectPanel, view, notifyDefaultFailure } } describe('UiWorkspaceService', () => { @@ -326,10 +328,10 @@ describe('UiWorkspaceService', () => { }) expect(b.workspaces.initializeDefault).toHaveBeenCalledExactlyOnceWith({ directoryName, title }, expect.any(AbortSignal)) expect(b.sessions.create).toHaveBeenCalledWith({ workspaceId: wid('default') }) - expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(false) + expect(b.notifyDefaultFailure).not.toHaveBeenCalled() }) - it('leaves an ineligible empty installation without a Session or failure dialog', async () => { + it('leaves an ineligible empty installation without a Session or failure notice', async () => { const b = bench({ workspaces: workspaceState(), sessions: sessionState() }) await setImmediate() b.workspaces.list.set(workspaceState()) @@ -337,7 +339,7 @@ describe('UiWorkspaceService', () => { await setImmediate() expect(b.workspaces.initializeDefault).toHaveBeenCalledOnce() expect(b.sessions.create).not.toHaveBeenCalled() - expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(false) + expect(b.notifyDefaultFailure).not.toHaveBeenCalled() }) it('requires explicit selection when the startup Session list contains history', async () => { @@ -351,13 +353,12 @@ describe('UiWorkspaceService', () => { const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => { workspaces.initializeDefault.mockRejectedValueOnce(new Error('denied')) } }) - await vi.waitFor(() => { expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(true) }) - b.uiWorkspace.defaultFailure.set(false) + await vi.waitFor(() => { expect(b.notifyDefaultFailure).toHaveBeenCalledOnce() }) b.workspaces.list.set(workspaceState()) await setImmediate() expect(b.workspaces.initializeDefault).toHaveBeenCalledOnce() expect(b.sessions.create).not.toHaveBeenCalled() - expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(false) + expect(b.notifyDefaultFailure).toHaveBeenCalledOnce() }) it.each(['session', 'panel', 'disposal'] as const)('cancels startup directory preparation after %s navigation', async (kind) => { @@ -373,27 +374,43 @@ describe('UiWorkspaceService', () => { await setImmediate() expect(b.sessions.create).not.toHaveBeenCalled() expect(b.sessions.retain.mock.calls.map(args => args[0])).toEqual(kind === 'session' ? [sid('manual')] : []) - expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(false) + expect(b.notifyDefaultFailure).not.toHaveBeenCalled() }) - it('retains a prepared Workspace when its Session fails and suppresses a superseded failure', async () => { - for (const superseded of [false, true]) { - const created = Promise.withResolvers() - const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => { - workspaces.initializeDefault.mockImplementationOnce(async () => { - const item = workspace('default') - workspaces.list.set(workspaceState([item])) - return item - }) - }, configureSessions: (sessions) => { sessions.create.mockReturnValueOnce(created.promise) } }) - await vi.waitFor(() => { expect(b.sessions.create).toHaveBeenCalledOnce() }) - if (superseded) b.layout.selectPanel('other-panel' as MainPanelId) - created.reject(new Error('session failed')) - await setImmediate() - expect(b.workspaces.list.getSnapshot().items).toEqual([workspace('default')]) - expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(!superseded) - expect(b.sessions.retain).not.toHaveBeenCalled() - } + it.each(['session', 'panel', 'disposal'] as const)('suppresses a startup directory failure after %s navigation', async (kind) => { + const pending = Promise.withResolvers() + const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => { + workspaces.initializeDefault.mockReturnValueOnce(pending.promise) + } }) + if (kind === 'session') b.uiWorkspace.openSession(sid('manual')) + else if (kind === 'panel') b.layout.selectPanel('other-panel' as MainPanelId) + else await b.ctx.fiber.dispose() + pending.reject(new Error('late failure')) + await setImmediate() + expect(b.sessions.create).not.toHaveBeenCalled() + expect(b.notifyDefaultFailure).not.toHaveBeenCalled() + }) + + it.each([false, true])('reports Session failure without a directory error and retains the Workspace (superseded: %s)', async (superseded) => { + const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const created = Promise.withResolvers() + const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => { + workspaces.initializeDefault.mockImplementationOnce(async () => { + const item = workspace('default') + workspaces.list.set(workspaceState([item])) + return item + }) + }, configureSessions: (sessions) => { sessions.create.mockReturnValueOnce(created.promise) } }) + await vi.waitFor(() => { expect(b.sessions.create).toHaveBeenCalledOnce() }) + if (superseded) b.layout.selectPanel('other-panel' as MainPanelId) + const failure = new Error('session failed') + created.reject(failure) + await vi.waitFor(() => { + expect(warning).toHaveBeenCalledExactlyOnceWith('initial Session restoration failed:', failure) + }) + expect(b.workspaces.list.getSnapshot().items).toEqual([workspace('default')]) + expect(b.notifyDefaultFailure).not.toHaveBeenCalled() + expect(b.sessions.retain).not.toHaveBeenCalled() }) it('retains an explicit main target before revealing its Conversation', () => { From 31e6b3f15061b64cc2827492055b2ce8914945bb Mon Sep 17 00:00:00 2001 From: Turtle Date: Sun, 20 Sep 2026 20:45:23 +0800 Subject: [PATCH 14/27] fix(client): rotate every ongoing StateDot loader in phase (#4737) CSS animations start when their element is inserted, so loaders mounted at different moments rotated out of step in the sidebar session list. The ongoing loader now pins its spin and dash animations to document time zero on mount so every visible loader shares one phase. --- .../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/StateDot.module.css | 3 ++- .../client/ui-primitives/src/StateDot.tsx | 15 ++++++++++++++ .../tests/state-dot.client.spec.tsx | 20 ++++++++++++++++++- 6 files changed, 40 insertions(+), 6 deletions(-) diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 52a8d99d49..dde0b3eec5 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-primitives/README.md -README.md: 09950210eaef57a290362037f3d603366fe00168 -README.zh.md: aa95cbf1ce7fa79c3d1d5466ca8ed4d6942ad03e +README.md: 12fe2648e383189198ff972709819e6f1eb4c02f +README.zh.md: 3c6f62fee22c5ad7e750c860724f60ca6dd9fbcf diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index 09950210ea..12fe2648e3 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -44,7 +44,7 @@ Check this table before writing a control in a feature package. A plugin cannot | `Pill` | Selectable capsule button for view switchers and filters; takes `active` and `onClick`. | | `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. | | `Tag` | Read-only capsule badge; `tone` selects one of eight palettes. | -| `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. `aria-hidden`, so the render site owns the name. | +| `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 so every visible loader rotates in phase. `aria-hidden`, so the render site owns the name. | | `ConnectionIndicator` | Inline connection-recovery control across outage, retry, and recovered states. | | `DisclosureRow` | 24px compact disclosure that lays title and content side by side. | | `Modal` | Centered dialog over a page mask. | diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index aa95cbf1ce..3c6f62fee2 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -44,7 +44,7 @@ kind: "package-library" | `Pill` | 可选中的胶囊按钮,用于视图切换与筛选器;接受 `active` 与 `onClick`。 | | `SegmentedTabs` | 受控的等宽分段标签,支持滑动指示条及左/右方向键、Home、End 导航。调用方提供文案、标签与面板 id,以及面板内容。 | | `Tag` | 只读胶囊徽章;`tone` 选择八种配色之一。 | -| `StateDot` | 10px 槽内的绿色 `done`、琥珀色 `warning`、红色 `error`、中性灰色 `idle` 圆点,以及 tertiary 灰色 14px 旋转 `ongoing` loading。它是 `aria-hidden` 的,名称由渲染点提供。 | +| `StateDot` | 10px 槽内的绿色 `done`、琥珀色 `warning`、红色 `error`、中性灰色 `idle` 圆点,以及 tertiary 灰色 14px 旋转 `ongoing` loading,其动画固定到文档时间零点,所以所有可见 loading 同相旋转。它是 `aria-hidden` 的,名称由渲染点提供。 | | `ConnectionIndicator` | 行内连接恢复控件,覆盖断线、重试与已恢复三种状态。 | | `DisclosureRow` | 24px 紧凑折叠行,标题与内容左右排列。 | | `Modal` | 页面遮罩之上的居中对话框。 | diff --git a/packages/client/ui-primitives/src/StateDot.module.css b/packages/client/ui-primitives/src/StateDot.module.css index 6a77a4e127..186e54eb57 100644 --- a/packages/client/ui-primitives/src/StateDot.module.css +++ b/packages/client/ui-primitives/src/StateDot.module.css @@ -32,7 +32,8 @@ } /* Ongoing is the sole non-dot state: a quiet full ring sits behind a centered - * breathing arc while the complete glyph rotates continuously. */ + * breathing arc while the complete glyph rotates continuously. Both animations + * share one 1.5s period so pinning their start times aligns them together. */ .spinner { flex: none; color: var(--dsw-alias-label-tertiary); diff --git a/packages/client/ui-primitives/src/StateDot.tsx b/packages/client/ui-primitives/src/StateDot.tsx index 05d869acfd..b0d84b89ec 100644 --- a/packages/client/ui-primitives/src/StateDot.tsx +++ b/packages/client/ui-primitives/src/StateDot.tsx @@ -7,6 +7,20 @@ import css from './StateDot.module.css' */ export type StateDotState = 'done' | 'warning' | 'ongoing' | 'error' | 'idle' +/** + * Pin the loader's CSS animations to document time zero. A CSS animation starts + * when its element is inserted, so loaders mounted at different moments rotate + * out of phase; one shared start time keeps every visible loader in step. + * @param element - the mounted loader, or null on unmount. + */ +function syncSpinner(element: SVGSVGElement | null): void { + if (element === null) return + // jsdom (the unit lane) implements no Web Animations despite lib.dom's + // non-optional typing; the optional call leaves that lane unsynced. + const spinner = element as { getAnimations?: SVGSVGElement['getAnimations'] } + for (const animation of spinner.getAnimations?.({ subtree: true }) ?? []) animation.startTime = 0 +} + /** * Render a state dot. * @param props.state - which of `done`, `warning`, `ongoing`, `error`, or `idle` to show. @@ -23,6 +37,7 @@ export function StateDot({ state, size, className }: { if (state === 'ongoing') { return ( { expect(bad('paused')).toBe('paused') }) }) + +describe('StateDot ongoing phase', () => { + it('pins every loader animation to document time zero on mount', () => { + const animations = [{ startTime: 42 }, { startTime: 7 }] + const getAnimations = vi.fn(() => animations) + const proto = SVGElement.prototype as { getAnimations?: () => { startTime: number }[] } + proto.getAnimations = getAnimations + try { + const { unmount } = render() + expect(getAnimations).toHaveBeenCalledWith({ subtree: true }) + expect(animations.map(animation => animation.startTime)).toEqual([0, 0]) + unmount() + expect(getAnimations).toHaveBeenCalledTimes(1) + } finally { + delete proto.getAnimations + } + }) +}) From 942e496ce7e4e72f5fe094c1428a46d07a4fafa7 Mon Sep 17 00:00:00 2001 From: liyao Date: Sun, 20 Sep 2026 20:45:29 +0800 Subject: [PATCH 15/27] fix(desktop): declare macOS bundle localizations --- apps/desktop/README.i18n.yaml | 4 ++-- apps/desktop/README.md | 2 +- apps/desktop/README.zh.md | 2 +- apps/desktop/scripts/electron-builder-config.mjs | 2 ++ 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 79e9bfbae3..067c49e554 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write apps/desktop/README.md -README.md: 94d09c628d6bb40933f95cd3874d412ab18521df -README.zh.md: bfb156bfaa0400799498eabb6034f32c2d50e7f3 +README.md: 8f8c4f87c2b254d123336a0ba723e66bf01fe11d +README.zh.md: 6537a2b2897d223fcd3a54725312c0bf78c4d412 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 94d09c628d..8f8c4f87c2 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -52,7 +52,7 @@ The `dsh-app://shell/` origin serves packaged update documents, scripts, and sty The product UI retains Web actions, including "Open In..." through the shared authenticated HTTP routes. Desktop uses Web's automatic directory-picker selection and initializes new profiles with the shared Web template's bundles. -Electron chooses typed English or Chinese shell copy from its application locale and falls back to English. On Windows, the main document's language updates desktop menus, recovery and update prompts. The repository Client UI i18n gate checks desktop sources. +Electron chooses typed English or Chinese shell copy from its application locale and falls back to English. The macOS application bundle declares English and Simplified Chinese in `CFBundleLocalizations`, allowing macOS to match the initial application language to the user’s preferred languages. Saved Client UI language preferences still take precedence for the main interface. On Windows, the main document's language updates desktop menus, recovery and update prompts. The repository Client UI i18n gate checks desktop sources. Windows uses a 40-DIP caption with native window controls and colors synchronized from the application palette. Localized Application and Edit entries beside the sidebar toggle open native popup menus. They mount only after the application frame publishes its shell overlay seat, and remain absent during startup loading. Application provides Check for Updates and Exit; Edit provides undo, redo, cut, copy, paste, delete, and select all by sending the corresponding keys to the focused editor. Plugin management uses the main application's Plugins page. No separate native menu row appears on Alt. Other platforms retain their native menus. Editable fields retain keyboard commands and a context menu without shortcut labels; Chromium supplies command availability, and selected read-only text offers Copy. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index bfb156bfaa..6537a2b289 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -52,7 +52,7 @@ Electron 拥有 `$DSH_HOME/profiles/desktop`。其 `dependencies` 包含 pnpm 产品 UI 保留 Web 操作,包括通过共享认证 HTTP 路由执行的“打开方式…”。Desktop 使用 Web 的自动目录选择机制,并以共享 Web 模板的 bundle 列表初始化新 profile。 -Electron 根据应用语言选择类型化的英文或中文 shell 文案,并回退到英文。在 Windows 上,主文档的语言会更新桌面菜单、恢复与更新提示。仓库 Client UI i18n 检查覆盖桌面端源码。 +Electron 根据应用语言选择类型化的英文或中文 shell 文案,并回退到英文。macOS 应用包通过 `CFBundleLocalizations` 声明支持英语和简体中文,让 macOS 根据用户的首选语言匹配初始应用语言。主界面仍优先使用已保存的 Client UI 语言偏好。在 Windows 上,主文档的语言会更新桌面菜单、恢复与更新提示。仓库 Client UI i18n 检查覆盖桌面端源码。 Windows 使用 40 DIP 顶栏,保留原生窗口按钮,颜色随应用调色板同步。侧栏开关旁的本地化“应用”和“编辑”入口打开原生弹出菜单。仅当应用框架发布 shell overlay 席位后才挂载菜单,启动加载期间不显示。“应用”提供检查更新和退出;“编辑”向当前编辑器发送对应按键,提供撤销、重做、剪切、复制、粘贴、删除和全选。插件管理使用主应用的“插件”页面。按 Alt 不会出现额外的原生菜单行。其他平台保留原生菜单。可编辑区域保留快捷键和不带快捷键标注的右键菜单;命令可用状态由 Chromium 提供,选中的只读文本提供“复制”命令。 顶栏菜单保留鼠标和键盘操作,顶栏中的 Web 控件仍可触达。共享 DOM 只约束展示,不构成安全边界:产品脚本可以隐藏蒙层,但不能借此清除主进程策略或授权安装。更新操作与状态通过隔离预加载和壳 frame 之间的私有 MessageChannel 传递。 diff --git a/apps/desktop/scripts/electron-builder-config.mjs b/apps/desktop/scripts/electron-builder-config.mjs index cf2f76768f..dd4b00d24c 100644 --- a/apps/desktop/scripts/electron-builder-config.mjs +++ b/apps/desktop/scripts/electron-builder-config.mjs @@ -126,6 +126,8 @@ export function createElectronBuilderConfig( mac: { icon: fileURLToPath(new URL('../resources/icon-macos.png', import.meta.url)), category: 'public.app-category.developer-tools', + // macOS matches the application locale against this bundle, not Electron Framework resources. + extendInfo: { CFBundleLocalizations: ['en', 'zh_CN'] }, identity: macOSSigning?.signingIdentity, forceCodeSigning: true, hardenedRuntime: true, From 93ad804bf1189e552e6d089df15e3c8e809d2ffe Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Sun, 20 Sep 2026 22:36:33 +0800 Subject: [PATCH 16/27] fix(web): report a refused new session through the Workspace notice MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An explicit New Session (sidebar and header buttons, the workspace row button, and the hero workspace pick) whose `session.create` the Host refuses — for example a default preset whose composition names a plugin that no longer resolves (`agent-preset/invalid`) — was only logged with `console.warn`, so the click looked like it did nothing. `openWorkspace` now shows the failure through the shared Workspace notice as a `createFailed` toast quoting the Host's stable code and message on the long hold, then rethrows as before. Startup restoration does not go through `openWorkspace` and stays console-only. --- packages/client/ui-workspace/README.i18n.yaml | 4 +- packages/client/ui-workspace/README.md | 2 +- packages/client/ui-workspace/README.zh.md | 2 +- .../ui-workspace/src/client/contract/slots.ts | 2 + .../client/ui-workspace/src/client/index.ts | 3 +- .../client/ui-workspace/src/client/locales.ts | 2 + .../ui-workspace/src/client/navigation.ts | 43 ++++++++++++--- .../client/session-actions/RowActionToast.tsx | 24 ++++++-- .../tests/session-actions.client.spec.tsx | 18 ++++++ .../tests/workspaces-service.client.spec.ts | 55 +++++++++++++++---- .../src/client/api-catalog.ts | 3 +- 11 files changed, 129 insertions(+), 29 deletions(-) diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index 81d24fe35b..6c1b132770 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-workspace/README.md -README.md: 92e2f231ec2e25aa1716f03338a980f2c2269d16 -README.zh.md: e490c4ebe63a0e11e1892d8bc02693ab63d12277 +README.md: d4396fd07a05791285f44a01a6cfb17aeac1ebe9 +README.zh.md: 31dca87e21c620271f5fe7307f07f9f437247742 diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index 92e2f231ec..d4396fd07a 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -69,7 +69,7 @@ The value is intentionally best effort for cold Sessions. An identity-matching u Navigation and startup restoration obtain the selected Session's projections from its `follow`; neither issues a separate projection refresh for that Session or its parent. -New Session tries to acquire the first eligible blank in catalog order; startup restoration tries the saved blank. If that writer is held, navigation creates a new Session without trying other blanks. Other acquisition failures abort the request and are currently reported only to the console. Released blanks retain their slash-command state when reused. Later navigation cancels a pending startup selection. +New Session tries to acquire the first eligible blank in catalog order; startup restoration tries the saved blank. If that writer is held, navigation creates a new Session without trying other blanks. Other acquisition failures abort the request: an explicit New Session or hero Workspace pick shows the failure as a transient notice quoting the Host's code and message (for example a preset that fails to mount), while startup restoration reports only to the console. Released blanks retain their slash-command state when reused. Later navigation cancels a pending startup selection. Once both Workspace and Session startup baselines are ready, an empty installation calls `workspaces.initializeDefault` and creates or reuses its blank Session. The composer becomes editable when that Session is selected; no message is submitted automatically. Later navigation or owner disposal prevents startup from selecting its result. Ineligible first use leaves the folder picker available without an error. Default Workspace creation failure shows a transient notice directing the user to Choose workspace, and is not retried until the next startup. Session creation failures use the ordinary restoration error handling. The registered Workspace remains available if Session creation or later submission fails. diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index e490c4ebe6..31dca87e21 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -69,7 +69,7 @@ Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示** 导航和启动恢复通过所选 Session 的 `follow` 获取投影,不会另行刷新该 Session 或其父会话的投影。 -新建会话尝试获取列表中第一个符合条件的空白会话;启动恢复尝试已保存的空白会话。若该写锁被占用,导航直接新建 Session,不再尝试其他空白会话。其他获取错误会中止请求,目前只报告到控制台。已释放的空白会话被复用时保留 slash 命令状态。后续导航会取消尚未完成的启动选择。 +新建会话尝试获取列表中第一个符合条件的空白会话;启动恢复尝试已保存的空白会话。若该写锁被占用,导航直接新建 Session,不再尝试其他空白会话。其他获取错误会中止请求:显式新建会话或在 hero 中选择工作区时,失败以短暂提示展示,引用 Host 的错误码和消息(例如 preset 挂载失败);启动恢复仍只报告到控制台。已释放的空白会话被复用时保留 slash 命令状态。后续导航会取消尚未完成的启动选择。 Workspace 和 Session 的启动基线均就绪后,空安装环境调用 `workspaces.initializeDefault`,创建或复用其空白 Session。选中该 Session 后输入框才可编辑,不会自动提交消息。后续导航或所属上下文销毁会阻止启动流程选中其结果。不符合首次使用条件时仍可选择文件夹,不显示错误。默认工作区创建失败时显示短暂提示,引导用户通过“选择工作区”选择文件夹,直到下次启动才重试。Session 创建失败沿用普通的恢复错误处理。登记成功的工作区在 Session 创建或后续提交失败时仍然保留。 diff --git a/packages/client/ui-workspace/src/client/contract/slots.ts b/packages/client/ui-workspace/src/client/contract/slots.ts index 36ab1850d4..0bd651602a 100644 --- a/packages/client/ui-workspace/src/client/contract/slots.ts +++ b/packages/client/ui-workspace/src/client/contract/slots.ts @@ -245,6 +245,8 @@ export type RowToast = | { kind: 'unpinFailed' } | { kind: 'archivedNotOpenable' } | { kind: 'defaultWorkspaceFailed' } + /** An explicit New Session request the Host refused; `message` is the failure in the Host's own words, untranslated. */ + | { kind: 'createFailed'; message: string } /** The notice on display; `seq` keys remounts so a repeated notice restarts its hold. */ export type RowToastState = RowToast & { seq: number } diff --git a/packages/client/ui-workspace/src/client/index.ts b/packages/client/ui-workspace/src/client/index.ts index 7c821033d6..2339aa77f0 100644 --- a/packages/client/ui-workspace/src/client/index.ts +++ b/packages/client/ui-workspace/src/client/index.ts @@ -107,8 +107,7 @@ export function apply(ctx: Context): void { let toastSeq = 0 const notify = (toast: RowToast): void => { rowToast.set({ ...toast, seq: ++toastSeq }) } const uiWorkspace = new UiWorkspaceService( - ctx, ctx.remote.directoryPicker, workspaces, sessions, viewInstance.actions, - () => { notify({ kind: 'defaultWorkspaceFailed' }) }, + ctx, ctx.remote.directoryPicker, workspaces, sessions, viewInstance.actions, notify, ) ctx.slots.provideRoot({ hooks: { workspaces: workspaces.list } }) ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-workspace: dictionaries') diff --git a/packages/client/ui-workspace/src/client/locales.ts b/packages/client/ui-workspace/src/client/locales.ts index 3ecc46741f..203811d38c 100644 --- a/packages/client/ui-workspace/src/client/locales.ts +++ b/packages/client/ui-workspace/src/client/locales.ts @@ -62,6 +62,7 @@ export const zh = { 'toast.archivedFilter': '筛选已归档会话', 'toast.pinFailed': '置顶失败,请稍后重试', 'toast.unpinFailed': '取消置顶失败,请稍后重试', + 'toast.createFailed': '新建会话失败:{message}', 'sessions.count.one': '{n} 个会话', 'sessions.count.other': '{n} 个会话', 'actions.workspace.aria': '工作区“{name}”的操作', @@ -157,6 +158,7 @@ export const en = { 'toast.archivedFilter': 'filter archived sessions', 'toast.pinFailed': 'Pin failed. Try again later.', 'toast.unpinFailed': 'Unpin failed. Try again later.', + 'toast.createFailed': 'New session failed: {message}', 'sessions.count.one': '{n} session', 'sessions.count.other': '{n} sessions', 'actions.workspace.aria': 'Workspace actions for {name}', diff --git a/packages/client/ui-workspace/src/client/navigation.ts b/packages/client/ui-workspace/src/client/navigation.ts index 139e35076a..4a05f3fc62 100644 --- a/packages/client/ui-workspace/src/client/navigation.ts +++ b/packages/client/ui-workspace/src/client/navigation.ts @@ -17,6 +17,7 @@ import type { import type { SessionId } from '@deepseek-ai/dsh-session/types' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type {} from '@deepseek-ai/dsh-client-locale/client' +import type { RowToast } from './contract/slots.ts' import { en, zh } from './locales.ts' import { pinOrderAccounts, pinOrderSource } from './pin-order.ts' import type { WorkspaceViewStoreActions } from './stores.ts' @@ -38,6 +39,7 @@ export interface UiWorkspace { * @param workspaceId - target Workspace. * @param beforeOpen - optional synchronous preparation for the selected Session, skipped after supersession. * @returns completion; a superseded request may create a Session but does not open it. + * @throws when the Session cannot be created; the failure is also shown through the Workspace notice. */ openWorkspace(workspaceId: WorkspaceId, beforeOpen?: (sessionId: SessionId) => void): Promise /** @@ -53,7 +55,8 @@ export interface UiWorkspace { */ connectWorkspace(workspaceId: WorkspaceId): Promise /** - * Start a New Session flow and navigate to its Session. + * Start a New Session flow and navigate to its Session; a creation the Host + * refuses is shown through the Workspace notice and leaves the selection as it was. * @param workspaceId - explicit target; absent inherits the current or most recent Workspace. */ startSession(workspaceId?: WorkspaceId): void @@ -133,7 +136,7 @@ class UiWorkspaceService extends Service implements UiWorkspace { * @param workspaces - pure Workspace Controller. * @param sessions - pure Session Controller. * @param view - the browser's viewing-store write set (one instance shared with its registration). - * @param notifyDefaultFailure - show the startup creation failure through the Workspace notice channel. + * @param notify - show one notice through the Workspace notice channel. */ constructor( ctx: Context, @@ -141,7 +144,7 @@ class UiWorkspaceService extends Service implements UiWorkspace { private readonly workspaces: IWorkspaces, private readonly sessions: ISessions, private readonly view: Pick, - private readonly notifyDefaultFailure: () => void, + private readonly notify: (toast: RowToast) => void, ) { super(ctx, 'uiWorkspace') ctx.effect(() => { @@ -187,9 +190,7 @@ class UiWorkspaceService extends Service implements UiWorkspace { try { return await this.sessions.create({ workspaceId, sessionId }) } catch (error: unknown) { - // Client plugin bundles do not share error-class identity. - if (!(error instanceof Error) || error.name !== 'SessionCreateError' - || (error as SessionCreateError).rpcError.code !== 'session/writer-held') throw error + if (sessionCreateErrorOf(error)?.rpcError.code !== 'session/writer-held') throw error return this.sessions.create({ workspaceId }) } } @@ -200,7 +201,15 @@ class UiWorkspaceService extends Service implements UiWorkspace { async openWorkspace(workspaceId: WorkspaceId, beforeOpen?: (sessionId: SessionId) => void): Promise { const navigation = AbortSignal.any([this.ctx.layout.beginNavigation(), this.lifetime.signal]) - const sessionId = await this.connectWorkspace(workspaceId) + let sessionId: SessionId + try { + sessionId = await this.connectWorkspace(workspaceId) + } catch (error: unknown) { + // The user asked for this Session, so the refusal is theirs to read; + // startup restoration goes through connectWorkspace directly and stays quiet. + this.notify({ kind: 'createFailed', message: creationFailureMessage(error) }) + throw error + } if (navigation.aborted) return this.replaceMain(sessionId, navigation, 'reveal', beforeOpen) } @@ -344,7 +353,7 @@ class UiWorkspaceService extends Service implements UiWorkspace { title, }, signal) } catch (_error: unknown) { - if (!signal.aborted) this.notifyDefaultFailure() + if (!signal.aborted) this.notify({ kind: 'defaultWorkspaceFailed' }) return undefined } } @@ -400,6 +409,24 @@ class UiWorkspaceService extends Service implements UiWorkspace { } +/** + * The Session Controller's creation failure `error` is, or undefined. Client + * plugin bundles do not share error-class identity, so the name decides. + */ +function sessionCreateErrorOf(error: unknown): SessionCreateError | undefined { + return error instanceof Error && error.name === 'SessionCreateError' ? error as SessionCreateError : undefined +} + +/** + * The words a failed Session creation is reported in: a Host refusal keeps its + * stable code and message; any other failure keeps its own message. + */ +function creationFailureMessage(error: unknown): string { + const refused = sessionCreateErrorOf(error) + if (refused !== undefined) return `${refused.rpcError.code}: ${refused.rpcError.message}` + return error instanceof Error ? error.message : String(error) +} + /** Stable tie-breaking follows Host Workspace order. */ function recentWorkspace( workspaces: readonly WorkspaceView[], diff --git a/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx b/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx index c5a3caccc6..7833409ba8 100644 --- a/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx +++ b/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx @@ -5,12 +5,17 @@ import { IconWarningOutlineRegular, Toast } from '@deepseek-ai/dsh-client-ui-primitives' import type { RowToastProps } from '../contract/slots.ts' -/** Hold for the actionable archived notice: two buttons need a longer read-and-react window than a plain notice. */ -const ARCHIVED_TOAST_HOLD_MS = 6000 +/** + * Hold for the notices that take longer to read than a one-line warning: the + * actionable archived notice (two buttons to react to) and a refused Session + * creation, which quotes the Host's reason. + */ +const LONG_TOAST_HOLD_MS = 6000 /** * Render the current notice: the archived notice with its undo - * and show-archived actions on a 6 s hold, or a plain warning for a failed + * and show-archived actions on a 6 s hold, a refused Session creation with + * the Host's reason on the same hold, or a plain warning for a failed * pin, an archived row that was clicked, or default Workspace creation. * @param props - the notice hook, its dismissal, the two archived-notice actions, and the locale seat. * @returns the notice on display, or null. @@ -25,7 +30,7 @@ export function RowActionToast({ useToast, dismissToast, undoArchive, showArchiv key={`toast-${String(toast.seq)}`} text={t('toast.archived')} tone="success" - holdMs={ARCHIVED_TOAST_HOLD_MS} + holdMs={LONG_TOAST_HOLD_MS} actions={[ { label: t('toast.archivedUndo'), onClick: () => { dismissToast(); undoArchive(sessionId) } }, { prefix: t('toast.archivedOr'), label: t('toast.archivedFilter'), onClick: () => { dismissToast(); showArchived() } }, @@ -34,6 +39,17 @@ export function RowActionToast({ useToast, dismissToast, undoArchive, showArchiv /> ) } + if (toast.kind === 'createFailed') { + return ( + } + holdMs={LONG_TOAST_HOLD_MS} + onDone={dismissToast} + /> + ) + } const text = toast.kind === 'pinFailed' ? t('toast.pinFailed') : toast.kind === 'unpinFailed' ? t('toast.unpinFailed') diff --git a/packages/client/ui-workspace/tests/session-actions.client.spec.tsx b/packages/client/ui-workspace/tests/session-actions.client.spec.tsx index c7e3b1150d..bce8cdf2e6 100644 --- a/packages/client/ui-workspace/tests/session-actions.client.spec.tsx +++ b/packages/client/ui-workspace/tests/session-actions.client.spec.tsx @@ -404,6 +404,24 @@ describe('RowActionToast', () => { } }) + it('shows a refused creation with the Host reason and holds it as long as the archived notice', () => { + vi.useFakeTimers() + try { + const { dismissToast, notify } = toastSurface() + notify({ kind: 'createFailed', message: 'agent-preset/invalid: agent-presets: preset "broken" failed to mount' }) + const alert = screen.getByRole('alert') + expect(alert.textContent).toBe('新建会话失败:agent-preset/invalid: agent-presets: preset "broken" failed to mount') + expect(alert.querySelector('button')).toBeNull() + act(() => { vi.advanceTimersByTime(4000) }) + expect(dismissToast).not.toHaveBeenCalled() + act(() => { vi.advanceTimersByTime(3000) }) + expect(dismissToast).toHaveBeenCalledOnce() + expect(screen.queryByRole('alert')).toBeNull() + } finally { + vi.useRealTimers() + } + }) + it('the archived notice holds longer than a plain notice, and a repeat restarts its hold', () => { vi.useFakeTimers() try { diff --git a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts index 75cfe81fcf..10fe3fdb65 100644 --- a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts +++ b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts @@ -16,6 +16,7 @@ import type { RemoteResult } from '@deepseek-ai/dsh-api-remotes/client' import { SessionId } from '@deepseek-ai/dsh-session/types' import { LayoutController } from '@deepseek-ai/dsh-client-ui-layout/client' import type { MainPanelId } from '@deepseek-ai/dsh-client-ui-layout/client' +import type { RowToast } from '../src/client/contract/slots.ts' import { DirectoryBrowseError, UiWorkspaceService } from '../src/client/navigation.ts' import { createWorkspaceViewStore, FLAT_SESSION_ORDER_KEY } from '../src/client/stores.ts' import { UNGROUPED_KEY } from '../src/client/tree.ts' @@ -294,16 +295,16 @@ function bench(options: BenchOptions = {}) { options.configureWorkspaces?.(workspaces) options.configureSessions?.(sessions) const view = createWorkspaceViewStore().create() - const notifyDefaultFailure = vi.fn() + const notify = vi.fn<(toast: RowToast) => void>() const uiWorkspace = new UiWorkspaceService( ctx, directoryPicker.remote, workspaces, sessions, view.actions, - notifyDefaultFailure, + notify, ) - return { ctx, directoryPicker, sessions, uiWorkspace, workspaces, layout, selectPanel, view, notifyDefaultFailure } + return { ctx, directoryPicker, sessions, uiWorkspace, workspaces, layout, selectPanel, view, notify } } describe('UiWorkspaceService', () => { @@ -328,7 +329,7 @@ describe('UiWorkspaceService', () => { }) expect(b.workspaces.initializeDefault).toHaveBeenCalledExactlyOnceWith({ directoryName, title }, expect.any(AbortSignal)) expect(b.sessions.create).toHaveBeenCalledWith({ workspaceId: wid('default') }) - expect(b.notifyDefaultFailure).not.toHaveBeenCalled() + expect(b.notify).not.toHaveBeenCalled() }) it('leaves an ineligible empty installation without a Session or failure notice', async () => { @@ -339,7 +340,7 @@ describe('UiWorkspaceService', () => { await setImmediate() expect(b.workspaces.initializeDefault).toHaveBeenCalledOnce() expect(b.sessions.create).not.toHaveBeenCalled() - expect(b.notifyDefaultFailure).not.toHaveBeenCalled() + expect(b.notify).not.toHaveBeenCalled() }) it('requires explicit selection when the startup Session list contains history', async () => { @@ -353,12 +354,12 @@ describe('UiWorkspaceService', () => { const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => { workspaces.initializeDefault.mockRejectedValueOnce(new Error('denied')) } }) - await vi.waitFor(() => { expect(b.notifyDefaultFailure).toHaveBeenCalledOnce() }) + await vi.waitFor(() => { expect(b.notify).toHaveBeenCalledExactlyOnceWith({ kind: 'defaultWorkspaceFailed' }) }) b.workspaces.list.set(workspaceState()) await setImmediate() expect(b.workspaces.initializeDefault).toHaveBeenCalledOnce() expect(b.sessions.create).not.toHaveBeenCalled() - expect(b.notifyDefaultFailure).toHaveBeenCalledOnce() + expect(b.notify).toHaveBeenCalledExactlyOnceWith({ kind: 'defaultWorkspaceFailed' }) }) it.each(['session', 'panel', 'disposal'] as const)('cancels startup directory preparation after %s navigation', async (kind) => { @@ -374,7 +375,7 @@ describe('UiWorkspaceService', () => { await setImmediate() expect(b.sessions.create).not.toHaveBeenCalled() expect(b.sessions.retain.mock.calls.map(args => args[0])).toEqual(kind === 'session' ? [sid('manual')] : []) - expect(b.notifyDefaultFailure).not.toHaveBeenCalled() + expect(b.notify).not.toHaveBeenCalled() }) it.each(['session', 'panel', 'disposal'] as const)('suppresses a startup directory failure after %s navigation', async (kind) => { @@ -388,7 +389,7 @@ describe('UiWorkspaceService', () => { pending.reject(new Error('late failure')) await setImmediate() expect(b.sessions.create).not.toHaveBeenCalled() - expect(b.notifyDefaultFailure).not.toHaveBeenCalled() + expect(b.notify).not.toHaveBeenCalled() }) it.each([false, true])('reports Session failure without a directory error and retains the Workspace (superseded: %s)', async (superseded) => { @@ -409,7 +410,7 @@ describe('UiWorkspaceService', () => { expect(warning).toHaveBeenCalledExactlyOnceWith('initial Session restoration failed:', failure) }) expect(b.workspaces.list.getSnapshot().items).toEqual([workspace('default')]) - expect(b.notifyDefaultFailure).not.toHaveBeenCalled() + expect(b.notify).not.toHaveBeenCalled() expect(b.sessions.retain).not.toHaveBeenCalled() }) @@ -641,6 +642,40 @@ describe('UiWorkspaceService', () => { expect(b.sessions.retain).not.toHaveBeenCalled() }) + it('reports a refused explicit Session creation through the Workspace notice', async () => { + const b = bench({ workspaces: workspaceState([workspace('a')]), sessions: sessionState() }) + // Startup restoration creates its own Session first and stays quiet on failure (pinned above). + await vi.waitFor(() => { expect(b.sessions.retain).toHaveBeenCalledOnce() }) + b.sessions.retain.mockClear() + expect(b.notify).not.toHaveBeenCalled() + const warning = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const refused = new SessionCreateError(new RemoteError( + 'agent-preset/invalid', + 'agent-presets: preset "broken" failed to mount: row "workflow-ptc" names a plugin that cannot be resolved', + { agentPreset: 'broken', reason: 'row "workflow-ptc" names a plugin that cannot be resolved' }, + ), undefined) + b.sessions.create.mockRejectedValueOnce(refused) + b.uiWorkspace.startSession(wid('a')) + await vi.waitFor(() => { + expect(b.notify).toHaveBeenCalledExactlyOnceWith({ + kind: 'createFailed', + message: 'agent-preset/invalid: agent-presets: preset "broken" failed to mount: row "workflow-ptc" names a plugin that cannot be resolved', + }) + }) + expect(warning).toHaveBeenCalledExactlyOnceWith('new session failed:', refused) + expect(b.sessions.retain).not.toHaveBeenCalled() + + // The hero picker reaches the same creation through openWorkspace; a + // failure that is not a Host refusal keeps its own message. + b.sessions.create.mockRejectedValueOnce(new Error('create failed')) + await expect(b.uiWorkspace.openWorkspace(wid('a'))).rejects.toThrow('create failed') + expect(b.notify).toHaveBeenLastCalledWith({ kind: 'createFailed', message: 'create failed' }) + b.sessions.create.mockRejectedValueOnce('rejected without an Error') + await expect(b.uiWorkspace.openWorkspace(wid('a'))).rejects.toBe('rejected without an Error') + expect(b.notify).toHaveBeenLastCalledWith({ kind: 'createFailed', message: 'rejected without an Error' }) + expect(b.notify).toHaveBeenCalledTimes(3) + }) + it('uses only an explicit Workspace or the recent-Workspace policy for new Sessions', async () => { const current = summary('current', { cwd: '/w/current-home', updatedAt: 1 }) const recent = summary('recent', { cwd: '/w/recent-home', updatedAt: 2 }) 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 d92592d81a..fe5358eef9 100644 --- a/packages/extensions/cordis-client-runner/src/client/api-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/api-catalog.ts @@ -345,6 +345,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ description: 'Connect a Workspace and open its Session unless a later navigation supersedes it.', parameters: [{ name: 'workspaceId', description: 'target Workspace.' }, { name: 'beforeOpen', description: 'optional synchronous preparation for the selected Session, skipped after supersession.' }], returns: 'completion; a superseded request may create a Session but does not open it.', + throws: ['when the Session cannot be created; the failure is also shown through the Workspace notice.'], }, { signature: 'forkSession(sessionId: SessionId): Promise', @@ -360,7 +361,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { signature: 'startSession(workspaceId?: WorkspaceId): void', - description: 'Start a New Session flow and navigate to its Session.', + description: 'Start a New Session flow and navigate to its Session; a creation the Host refuses is shown through the Workspace notice and leaves the selection as it was.', parameters: [{ name: 'workspaceId', description: 'explicit target; absent inherits the current or most recent Workspace.' }], }, { From 508329fe5799287c2e69dca15c27505dc911ba3d Mon Sep 17 00:00:00 2001 From: imccyu Date: Sun, 20 Sep 2026 20:56:49 +0800 Subject: [PATCH 17/27] feat(ui-chat): add presentation policy channel --- ...-presentation-policy-and-step-groups.zh.md | 276 ++++++++++++++++++ ...26-09-20-chat-work-details-migration.zh.md | 120 ++++++++ packages/client/ui-chat/README.i18n.yaml | 4 +- packages/client/ui-chat/README.md | 2 + packages/client/ui-chat/README.zh.md | 2 + packages/client/ui-chat/src/chat-settings.ts | 23 +- packages/client/ui-chat/src/client/apply.ts | 6 +- .../src/client/chat/AssistantMarkdown.tsx | 12 +- .../src/client/chat/AssistantNodeView.tsx | 10 +- .../ui-chat/src/client/chat/ChatNodeSeat.tsx | 19 +- .../ui-chat/src/client/chat/ChatView.tsx | 6 +- .../src/client/chat/ReasoningRow.module.css | 5 + .../ui-chat/src/client/chat/ReasoningRow.tsx | 54 ++-- .../client/chat/register-node-renderers.ts | 18 +- .../ui-chat/src/client/contract/slots.ts | 24 +- .../ui-chat/src/client/contract/snapshot.ts | 2 + .../turn-process-presentation.ts | 2 + packages/client/ui-chat/src/client/index.ts | 6 +- packages/client/ui-chat/src/client/locale.ts | 16 +- .../ui-chat/src/client/presentation-policy.ts | 70 +++++ .../src/client/settings/TranscriptViewRow.tsx | 28 +- .../ui-chat/src/client/transcript-view.ts | 13 +- packages/client/ui-chat/src/index.ts | 2 +- ...stant-markdown-path-images.client.spec.tsx | 3 + .../ui-chat/tests/chat-apply.client.spec.tsx | 6 +- .../tests/chat-branch-tails.client.spec.tsx | 2 + .../ui-chat/tests/chat-view.client.spec.tsx | 7 +- .../tests/coverage-tails.client.spec.tsx | 8 +- .../tests/gate-branch-tails.client.spec.tsx | 3 + .../tests/image-labels.client.spec.tsx | 4 + .../tests/presentation-fixture.client.ts | 10 + .../tests/reasoning-row.client.spec.tsx | 23 +- .../transcript-view-policy.client.spec.ts | 18 +- .../tests/transcript-view-row.client.spec.tsx | 8 +- .../ui-conversation/src/client/locales.ts | 8 +- .../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/DisclosureRow.tsx | 7 +- .../client/ui-skill/src/client/locales.ts | 2 +- 40 files changed, 716 insertions(+), 121 deletions(-) create mode 100644 .agents/notes/proposed/architecture/2026-09-20-chat-presentation-policy-and-step-groups.zh.md create mode 100644 .agents/notes/proposed/feature/2026-09-20-chat-work-details-migration.zh.md create mode 100644 packages/client/ui-chat/src/client/presentation-policy.ts create mode 100644 packages/client/ui-chat/tests/presentation-fixture.client.ts diff --git a/.agents/notes/proposed/architecture/2026-09-20-chat-presentation-policy-and-step-groups.zh.md b/.agents/notes/proposed/architecture/2026-09-20-chat-presentation-policy-and-step-groups.zh.md new file mode 100644 index 0000000000..88ee6a4986 --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-09-20-chat-presentation-policy-and-step-groups.zh.md @@ -0,0 +1,276 @@ +# Agent Note: Chat 展示策略通道与过程分组的基础架构 + +Status: proposed + +## 问题 + +Chat 的「对话显示」设置今天只有两档:`normal` 不折叠、`compact` 在轮次结束后把过程行折进一个整轮控件。设置值的流向是:`TranscriptViewPolicy.mode` 观察量注入 ChatView,ChatView 用 `useTranscriptView` 读成一个布尔值 `compactTranscript`,再作为 prop 传给 `ChatNodeList`,再传给每一个 `ChatNodeSeat`。另一个全局布尔值 `hasMore` 走同一条路,以 `historyIncomplete` 的名字进每个 seat。两个值一变,全部 seat 重渲染一遍,哪怕只有可折叠的那几个输出真的变了。 + +产品要把这个设置改成三档:简洁、详细、完全展开;并在简洁和详细两档里把回复之间的连续过程行归成可折叠的组。PR #4565 做过一次完整实现,合并八分钟后因性能回退被整体撤回。合并前后在本机的对照实测:长会话分页耗时 +27%,DOM 节点 +23%,堆内存 +14%,Trajectory 切换 +10%,全部仍在 CI 预算内;仓库现有六个基准没有任何一个覆盖「流式期间 reasoning 或工具 chunk 进入活动分组、分组重投影、seat 重渲染」这条它新增的热路径。 + +审阅那次实现,问题不在业务需求,在选型: + +- 模式被当成列表结构的输入。`ChatNodeList` 订阅整表 `layout`,按 range 生成 wrapper 组件;完全展开模式下 wrapper 消失。模式切换等于整棵列表重挂载,任何一次重新分组都重建 wrapper 的 key。 +- 模式进了 `ChatNodeOwnerProps`。每个 seat 的 owner 对象随模式变,所有业务渲染器跟着重渲染,包括与模式无关的用户消息、工具行、压缩标记。 +- 同一个 Assistant 节点在 seat 里被拆成 reasoning 与 response 两份派生对象,只为了让 wrapper 在 DOM 上包住前者不包住后者。master 的 `AssistantMarkdown` 早有 `reasoningHidden` 与 `revealProcess`,靠隐藏状态就能只藏 reasoning。 +- 基础设施行的 Chat 可见性由消费方过滤函数在四处各判一遍,而节点本身有 `visibility` 字段由 Definition 决定。 + +再往下一层,是一个信息流上的两难:分组的行要出现在成员之前,从组打开那一刻就该存在;但它要显示的内容,只有看到整轮所有事件的人才知道。事件驱动的 Context 模型里每个 Context 只收自己的事件,能看到整轮的只有 turn 级 Context,而它只能产出一个节点。 + +本记录给出一套基础架构,让三档模式与分组落地时满足下面的约束,并让后续产品变化只落在少数节点上。 + +## 目标与约束 + +下表是评审阶段已经确认的裁决,本方案不再重新讨论它们。 + +| 编号 | 裁决 | 含义 | +|---|---|---| +| 1 | 分组结构在 Definition 层定义 | 组的开合、成员范围、摘要由一个多重匹配本轮事件的 Definition 折叠出来,不由渲染层扫描节点得到 | +| 2 | 有限刷 seat | 切模式只重渲染 presentation 真正变化的 seat;流式 chunk 只重渲染所属 seat 和它所在组的组头;用户消息、回复、turn-tail 在这两种变化下零重渲染 | +| 3 | 一个 Context 一个节点 | 不引入「一个 Context 产出多个节点」,理由是绝大多数 Context 只会有一个元素,数组化让内存更零散 | +| 4 | 模式不开关 Definition | 注册变化会触发 registry 重建与全量重放,所有 seat 必刷;Definition 必须与模式无关 | +| 5 | 折叠按轮判定 | 一轮只要自己的 `turn/start` 已加载就可以折叠;被分页切开的最老一轮保持展开,本轮不优化 | +| 6 | 允许改 ui-conversation | 引擎可以改,但只做让方案正确成立所必需的小改动 | +| 7 | 本轮范围 | 只写代码与本记录;不写测试,不改其他文档;测试与文档在下一轮补 | + +有一条前置澄清:接受「切模式全屏重排版」不等于接受「所有 seat 重渲染」。浏览器重排是几何结果,seat 重渲染是 React 组件函数重跑,后者才是这里要限制的量。 + +## 可行的路线 + +围绕「组头这一行的身份从哪来、内容从哪来」,可行的路线有五条。 + +**路线 A,头成员的 seat 画组头。** 列表不变,builder 算出分组后告诉第一个成员的 seat「你是组头」,该 seat 在自己上方画标题,其余成员 seat 用现有 `hidden` 机制藏起来。零新概念。缺点是 seat 里出现「自身可见但只显示标题」的第三种状态,且标题寄生在一个业务节点的 seat 里。 + +**路线 α,每步一个 Context 当组头。** 增加一个 id 为 `turn:step` 的 Definition,在构建时读上一步的 `assistant-step` 数据判断自己是否新组开头,是则产出组头节点。组的内容由另一个 turn 级 Definition 发布成 Turn 数据供渲染器读取。 + +**路线 β,一个 Context 产出多个节点。** turn 级 Definition 一个人产出整轮控件加 N 个组头。 + +**路线 γ,父 Context 派生子 Context。** turn 级 fold 在开组时生成一个 `step-group` 子 Context 并把后续事件转发给它,子 Context 有自己的单个节点。引擎需要新增转发原语与重放级联。 + +**路线 δ,Definition 拥有结构,builder 物化行。** turn 级 Definition 折叠出组列表并发布为 Turn 数据;Chat builder 据此物化组头节点并给成员写归属;seat 用组合 selector 决定隐藏;引擎给 `ViewBuilder.apply` 的入参加一份「本次 flush 哪些 Location 数据换了引用」。 + +## 砍掉的路线与理由 + +**每组一个 Context 无法成立。** 引擎要求 `match(event)` 只看单个事件算出 id,「第几组」取决于前面有没有回复,单个事件算不出。这不是实现难度,是契约上的不可能。 + +**路线 α 与裁决 2 冲突。** 组头身份能算出,但内容要读整轮一份 Turn 数据,任何一组变化全轮组头都重渲染。改成去读 `turn.steps` 里后面几步的数据,又碰上组头节点不会因为后面的步到来而重建,读到的是陈旧引用。 + +**路线 β 被裁决 3 否决。** 见上表。 + +**路线 γ 现在不值。** 它在所有权上最纯,但要给 assembler 加转发与重放级联,是几百行的引擎核心改动。本记录把它保留为备选,条件写在末尾。 + +**路线 A 作为退路保留。** 如果 builder 物化节点在实践中被否决,退到 A;两者的结构来源相同,只差组头这一行的承载。 + +选择路线 δ。 + +## 方案 + +### 数据流 + +``` +事件流 + ──▶ step-groups Definition(turn 级 fold,多重匹配本轮事件) + ──▶ Turn 数据 step-groups:组列表,每组一个对象 + ──▶ Chat builder + ├─ 物化组头节点:一组一个 key,data 即组对象 + └─ 成员归属:按 step 映射到 key,写进 per-key presentation + ──▶ seat:hidden = f(策略字段, 角色, 展开状态) + ──▶ 组头渲染器:读自己节点的 data +展示策略 + ──▶ 渲染器:按 kind 注入的 hooks,选单个字段 + ──▶ seat:组合 selector,选出的是自己的结论 +``` + +引擎改动只有一处:assembler 在 flush 时把「哪些 Location 数据换了引用」随 `apply` 入参交给 builder。 + +### 各层职责 + +| 层 | 拥有 | 明确不拥有 | +|---|---|---| +| `step-groups` Definition | 组的开合、`headStep`、`closeStep`、工具计数与名称、运行中的工具;作为 Turn 数据发布 | 任何视图节点;成员是哪些节点 | +| Chat builder | 组头节点的身份与生命周期;成员归属;`turnStarted`;per-key presentation 的身份比较发布 | 读事件;自己算业务结构 | +| 展示策略对象 | 枚举到能力字段的映射 | 任何节点或 seat 状态 | +| seat | 用策略字段、角色、store 状态合成 hidden;把组的开合能力交给组头渲染器 | 判断组的边界 | +| 组头渲染器 | 标题、箭头、点击开合 | 组的内容来源 | +| assistant-step 渲染器 | 是否显示已完成推理的首行预览;作为组的关闭者时隐藏推理部分 | 组的边界 | + +### 组头节点的身份与生命周期 + +组头节点的 key 是 `step-group:${turn}:${headStep}`。`headStep` 在组打开那一刻就确定,之后任何事件都改不了「谁是第一个」,所以组头节点从打开起就存在并被复用,运行中不会换 key。组关闭只是它 data 里的 `closed` 从 false 变 true。 + +组头节点的锚点是该组头成员节点锚点减去一个合成偏移,位置紧贴在第一个成员之前。头成员的 Assistant 节点在流式期间锚在第一个可见 chunk,落盘后锚在消息事件,锚点会移动一次;组头随之移动一次,这是一次结构性更新,与 Assistant 节点自己的结构性更新同时发生,不额外增加次数。 + +组头节点属于整轮过程的一部分:整轮折叠时它随成员一起隐藏。它不在 `TURN_PROCESS_INDEPENDENT_KINDS` 里。 + +组头节点的 data 就是 fold 发布的组对象。已关闭的组对象引用永不改变,因此已关闭组头的 source 永不通知;正在运行的组每来一个改变它的事件换一个对象,只有这一组的组头重渲染。 + +### fold 状态机 + +`step-groups` Definition 的 id 是 turn 号,在 `turn/start` 上启动,匹配与 `turn-process` 同一批事件。State 是 `{ turn, groups, open }`,`groups` 是组对象数组,`open` 是当前打开组的下标或空。 + +| 事件 | 转移 | +|---|---| +| `tool/call` | 没有打开的组则以该事件的 step 开新组;计数加一;记录 distinct 工具名;把 callId 加入运行集合 | +| `tool/result` 追加 | 从运行集合移除 callId | +| `assistant/live-chunk` 推理 delta 含可见字符 | 没有打开的组则以该 chunk 的 step 开新组 | +| `assistant/live-chunk` 文本 delta 或文本块结束含可见字符 | 有打开的组则以该 chunk 的 step 关闭它 | +| `assistant/message` 追加 | 消息含可见推理则按推理规则处理,含可见回复则按文本规则处理;顺序是先推理后文本 | +| `turn/end` | 有打开的组则标记为被轮次结束关闭 | +| `step/start`、`step/end`、`llm/retry` | 不改变状态;重试行不属于任何组 | + +三条不变量: + +- 幂等。开组时已有打开的组则无操作;关组时组已关闭则无操作。live chunk 与落盘消息重复描述同一内容不会开两次或关两次,历史重放只有落盘消息也能得到同样的组列表。 +- 引用稳定。State 没变时 `update` 返回原对象;`groups` 数组只在组列表变化时换引用;已关闭的组对象永不替换。 +- 只向前折叠。不读邻居 Context,不读节点,不向后看。 + +Turn 数据发布:`buildLocationData` 只在 turn 阶段返回值,`groups` 引用不变时返回上一次发布的值,引擎据此不重新发布。没有 `turn/start` 的历史窗口用与 `turn-process` 相同的兜底:从已有匹配折叠出 State。 + +发布节奏:live chunk 走动画帧合并,其余立即。 + +### 成员归属规则 + +归属由 builder 按 step 判定,不用 seq 区间,因为 live chunk 的 seq 与落盘事件的 seq 不在一个尺度上。 + +| 节点 | 规则 | +|---|---| +| `tool-call`,step 为 s | 属于 `headStep ≤ s` 的最后一组。文本在同一 step 关闭了上一组之后的工具调用,会由 fold 以该 step 开出新组,所以「最后一组」总是正确的那一组 | +| `assistant-step`,step 为 s,且某组 `closeStep === s` | 角色为关闭者。节点保持可见;组折叠时只隐藏它的推理部分,用现有 `reasoningHidden` 机制 | +| `assistant-step`,step 为 s,其余情况 | 属于 `headStep ≤ s` 且 `s` 未越过 `closeStep` 的组,角色为成员 | +| `model-retry`、`turn-error`、`turn-max-tokens`、`turn-tail`、`user`、`steering` | 不属于任何组 | + +归属只在组列表变化时重算,成本是该轮节点数。流式 chunk 不改变组列表时,成员的 presentation 不发布。 + +组头行锚在最早的成员之前。一个组如果只有关闭者的推理而没有任何成员,比如一步里先推理后回复,组头行就锚在关闭者之前,这样被隐藏的推理仍然有一行可以点开。 + +### 分组变化怎样到达 builder + +fold 只发布 Turn 数据,没有视图节点。engine 的 `flush` 在 Location 数据有变化时会把 `timelineDirty` 置真并对所有活跃目标调用 `apply`,但 builder 不知道是哪一轮的哪个 key 变了。依赖「同一轮总有别的节点也在这次 flush 里变了」去推断,是巧合不是契约。 + +所以给 `ConversationViewBuilder.apply` 的入参增加可选的 `changedLocationData`:本次 flush 里换了引用的 Location 数据清单,每项含 `kind`、`turn`、可选 `step`、`key`。assembler 在 `applyDirtyLocationData` 里本来就逐条比较了前后引用,只是把比较结果收集起来交给 builder。Chat builder 只取 `key === 'step-groups'` 的轮次做重投影。入参可选,不传时 builder 退化为按本次 upsert 涉及的轮次重投影。 + +### seat 的 hidden 合成 + +seat 不再接收 `compactTranscript` 与 `historyIncomplete` 两个 prop。它通过 `usePresentation` 读策略,但选出的不是模式,而是自己的结论: + +```ts +const grouping = usePresentation(p => group === undefined ? 'none' : p.stepGrouping) +const foldCompleted = usePresentation(p => p.foldCompletedTurns) +``` + +不在任何组里的 seat,`grouping` 在三档下都是 `'none'`,值没变就不重渲染。`foldCompletedTurns` 在三档下都是 true,同理。selector hook 的底层是 `useSyncExternalStoreWithSelector`,只有选出的值变化才重渲染。 + +三个隐藏来源合成一个 `hidden`: + +| 来源 | 条件 | 揭示动作 | +|---|---|---| +| 整轮折叠 | 现有规则,`turnClosed && turnStarted && 有回复` 且未手动展开 | 打开整轮 | +| 组折叠 | `grouping === 'collapsed'`、角色为成员、组未手动展开 | 打开该组 | +| 组头在完全展开档 | 角色为组头且 `grouping === 'none'` | 无 | + +关闭者节点的推理部分单独隐藏:seat 通过 owner props 里的 `stepGroup.reasoningHidden` 告诉 assistant-step 渲染器。 + +组的展开状态进 chat store,key 是 `turn` 加 `headStep`,与整轮的手动展开状态并列。 + +### 刷新范围 + +下表是这套结构给出的保证,也是下一轮渲染次数测试的断言表。每一行断言的是精确集合,不是上限。 + +| 外部变化 | 允许重渲染的 | +|---|---| +| 运行中的组来一个推理 chunk | 该 assistant seat | +| 运行中的组来一个 `tool/call` | 该 tool seat,加这一组的组头 | +| 回复出现,组关闭 | 该 assistant seat,加这一组的组头;成员归属重算只发生在开关组时 | +| 新组打开 | 新组头进 `order`,一次结构重排;其他 seat 不刷 | +| 模式在简洁与详细之间切换 | 仅有已完成推理的 assistant-step 渲染器 | +| 模式切到完全展开或切回 | 仅成员与组头 seat | +| `performanceUsage` 切换 | 仅 turn-tail | +| 加载更早一页 | 新增 seat,加 presentation 变了的历史 seat | +| 语言切换 | 全部,作为对照 | + +### 展示策略对象 + +持久化的枚举与运行时词汇分开。枚举 `TranscriptViewMode` 是 `compact`、`detailed`、`expanded`,存档里的旧值 `normal` 读取时映射为 `detailed`,不回写。运行时词汇是派生的 `ChatPresentationPolicy`: + +| 字段 | compact | detailed | expanded | +|---|---|---|---| +| `foldCompletedTurns` | true | true | true | +| `stepGrouping` | collapsed | collapsed | none | +| `settledReasoningPreview` | false | true | true | + +映射只存在于一处。每档对应一个常量对象,同一档永远同一引用,所以派生观察量不需要自己的订阅簿记:`getSnapshot` 是查表,`subscribe` 直接转给模式观察量。 + +渲染器不比较枚举,只 select 自己需要的字段。策略观察量按 kind 注入:assistant-step 的注册通过 `inject.hooks.presentation` 拿到它,与 turn-tail 注入 `performanceUsage` 是同一写法。以后加第四档只改这张表,渲染器一个不动。 + +### 按轮折叠 + +per-key presentation 增加 `turnStarted`,来源是该轮 `turn/start` 是否在加载窗口内。seat 的折叠资格由 `turnStarted` 替代原来的全局 `!historyIncomplete`。分页加载完成时不再有任何全局 prop 变化,只有新增节点与它们所在轮的 presentation 变化。 + +### 复杂度契约 + +| 场景 | fold | builder | 发布 | +|---|---|---|---| +| 内容型 chunk,不改变组边界 | O(1) 状态转移,返回原对象 | 无重投影 | 零 | +| 改变组边界的事件 | O(1) | 只重投影所属轮,成本为该轮节点数 | 该轮内事实变化的 key | +| 结构变化与分页 | 按匹配的事件数 | 全量一次 | 事实变化的 key | +| 模式切换 | 无 | 无 | 无;重渲染由 seat 与渲染器的 selector 决定 | + +## 改动清单 + +| 包 | 文件 | 改动 | +|---|---|---| +| ui-conversation | `contract/conversation.ts` | 新增 `ConversationLocationDataUpdate`;`ConversationViewBuilder.apply` 入参增加可选 `changedLocationData` | +| ui-conversation | `conversation/assembler.ts` | `applyDirtyLocationData` 收集换了引用的 Location 数据并随 `apply` 传出 | +| ui-conversation | `index.ts` | 导出新类型 | +| ui-chat | `chat-settings.ts` | 三档枚举;schema 接受旧值 `normal` | +| ui-chat | `transcript-view.ts` | 读取时 `normal` 映射为 `detailed` | +| ui-chat | `presentation-policy.ts` 新增 | 策略对象、映射表、派生观察量 | +| ui-chat | `settings/TranscriptViewRow.tsx` | 三个选项 | +| ui-chat | `locale.ts` | 三档文案;组头文案 | +| ui-chat | `contract/slots.ts` | `ChatViewInjected.hooks.presentation`;`PresentationInjected`;`ChatNodeOwnerProps.stepGroup`;`StepGroupOwnerProps` | +| ui-chat | `contract/snapshot.ts` | `ChatTurnProcessPresentation.turnStarted`;`ChatNodeGroupPresentation`;`processSource` 的值改为 per-key 组合对象 | +| ui-chat | `contract/chat-nodes.ts` | `StepGroupChatData` | +| ui-chat | `contract/store.ts`、`stores.ts` | 组的手动展开状态与动作 | +| ui-chat | `conversation-nodes/common.ts` | 组头锚点偏移 | +| ui-chat | `conversation-nodes/step-groups.ts` 新增 | fold Definition 与 Turn 数据声明合并 | +| ui-chat | `conversation-nodes/step-group-nodes.ts` 新增 | 组头节点物化与成员归属投影 | +| ui-chat | `conversation-nodes/turn-process-presentation.ts` | `turnStarted`;组合 per-key presentation | +| ui-chat | `conversation-nodes/chat-snapshot-builder.ts` | 接入物化投影;消费 `changedLocationData`;store 支持删除 key | +| ui-chat | `conversation-nodes/register.ts` | 注册 fold Definition | +| ui-chat | `chat/ChatView.tsx` | 删除 `compactTranscript` 与 `historyIncomplete` 的传递;传 `usePresentation` | +| ui-chat | `chat/ChatNodeSeat.tsx` | 组合 selector;三个隐藏来源;`stepGroup` owner props | +| ui-chat | `chat/AssistantNodeView.tsx`、`chat/AssistantMarkdown.tsx`、`chat/ReasoningRow.tsx` | 注入策略;已完成推理的预览开关;关闭者的推理隐藏 | +| ui-chat | `chat/StepGroupNodeView.tsx` 新增 | 组头渲染器 | +| ui-chat | `chat/register-node-renderers.ts` | 注册组头渲染器;给 assistant-step 注入策略 | +| ui-chat | `apply.ts`、`index.ts` | 创建策略观察量并注入;导出类型 | + +本轮不改:README、i18n 配对文件、slot catalog、测试、快照。slot catalog 中 `ChatNodeOwnerProps` 的源码摘录与 key 列表需要在提 PR 前重新生成。 + +## 验收标准 + +下一轮补齐,本轮不实现。 + +**渲染次数隔离测试。** 在现有 `chat-view.client.spec` 的挂载方式上加计数:React Profiler 的 `onRender` 按 seat 计数,测试专用的计数渲染器注册进 `conversation.chat.node` 按 kind 计数。刺激与期望按「刷新范围」一节的表逐行断言精确集合。 + +**发布次数测试。** 同样的刺激下统计每个 key 的 source 通知次数,断言精确集合。 + +**fold 状态机单测。** 喂事件序列,断言组列表:开组、关组、同 step 先文本后工具开新组、轮次结束关组、幂等性、已关闭组对象引用不变、只有落盘消息的历史重放得到相同组列表。 + +**成员归属单测。** 给定组列表与该轮节点,断言每个 key 的角色。 + +**基准补位。** `conversation-fold` 增加带推理与工具的增量 apply 场景;`long-session-browser` 增加带工具与推理的流式 fixture。这是墙钟兜底,不是门禁。 + +## 风险与待决 + +- **builder 产出节点的边界。** 这是这套架构里第一次由视图 builder 产出节点。边界写死为:builder 只能从 Turn 或 Step 数据物化行,不能读事件,不能自己算业务结构。合成 key 用 `step-group:` 前缀,Context key 以数字开头,不会冲突。如果实践中被否决,退到路线 A。 +- **组头锚点随头成员移动一次。** 头成员是流式 Assistant 时,落盘让锚点从首个可见 chunk 移到消息事件,组头跟着移动一次。与 Assistant 自己的结构性更新同时发生。 +- **三档在本轮的实际差异。** 简洁与详细目前只差已完成推理的首行预览;运行中的详情标题、类别摘要等产品特性不在本轮。策略表已为它们留了位置。 +- **分页与半截轮。** 被分页切开的最老一轮不折叠、不分组;归属只按 step 计算,不受分页影响。 +- **组头文案。** 本轮只有「正在处理」与「已完成处理」加工具调用次数,类别摘要留给产品层。 +- **流式 chunk 的 step 字段。** `assistant/live-chunk` 事件携带 `step`,与 `turn-process` 的用法相同;若 chunk 缺少 step 则不开组。 + +## 备选保留:父 Context 派生子 Context + +如果 builder 物化节点在使用中暴露出比预期更多的边界问题,替代方案是给引擎加一个原语:Context 在 `update` 中可以派生一个指定 kind 与 id 的子 Context,并把后续匹配转发给它;子 Context 有自己的单个节点、自己的发布节奏与 Location。父 Context 重放时子 Context 按 id 对齐,未再派生的子 Context 按现有撤回规则转为隐藏。 + +它的收益是行的身份与内容都回到 Definition 层,一组一个 Context,没有数组碎片。代价是 assembler 要新增转发与重放级联,且 `match` 之外多出一条 Context 创建路径。切换条件:builder 物化节点的边界在两个以上业务里被突破,或成员归属的按 step 规则出现无法用 step 表达的用例。 diff --git a/.agents/notes/proposed/feature/2026-09-20-chat-work-details-migration.zh.md b/.agents/notes/proposed/feature/2026-09-20-chat-work-details-migration.zh.md new file mode 100644 index 0000000000..62381f453e --- /dev/null +++ b/.agents/notes/proposed/feature/2026-09-20-chat-work-details-migration.zh.md @@ -0,0 +1,120 @@ +# Agent Note: Chat 工作过程展示迁移进度 + +Status: proposed + +## 问题 + +PR #4565 同时包含三档展示设置、过程分组、整轮状态、触发通知、工具行视觉和基础设施行隐藏。整批迁移会把独立功能与列表重组混在一起,也难以逐项判断性能变化。需要一份按功能维护的进度表,先完成不依赖 step-group 的部分,再处理分组,避免遗漏原有产品需求。 + +## 方案 + +当前迁移目标是 `feat/chat-presentation-channel`。`pr-4565` worktree 保存原 PR 的重放内容,作为产品行为和实现的参考;`feat/chat-step-groups` 保存尚未接入当前通道的分组实验。不能仅凭分支名或提交记录判断完成情况,还要核对各 worktree 中未提交的代码。 + +本记录管理功能范围、当前实现和验收进度。[展示策略通道与过程分组的基础架构](../architecture/2026-09-20-chat-presentation-policy-and-step-groups.zh.md)保留架构路线及备选方案;本记录不替代它,也不把其中的方案视为已经实现。新记录没有完整取代既有架构决策,因此保留原记录,不做归档或删除。 + +本记录处于开发阶段,只维护中文版。新增迁移代码不自动暂存,不覆盖已有暂存内容。当前这一轮仅新增本记录,没有继续迁移功能代码。 + +### 状态定义 + +| 状态 | 含义 | +|---|---| +| 当前代码已有 | 已能在当前 worktree 源码中找到实现;不代表已提交、已发布或通过完整验收 | +| 待迁移 | 已纳入非分组迁移范围,当前尚未实现 | +| 分组阶段 | 产品需求保留,依赖分组结构或分组交互,暂不接入当前通道 | +| 待验收 | 需要行为、节点身份、刷新范围或浏览器性能证据;不能用编译结果代替 | + +### 当前通道已有的能力 + +| 能力 | compact | detailed | expanded | 实现状态 | 验收状态 | +|---|---|---|---|---|---| +| 三档设置与旧值读取 | 简洁 | 详细;旧值 `normal` 读作本档,不回写 | 完全展开 | 当前代码已有 | 待验收 | +| 按轮判断整轮折叠资格 | 本轮已结束、起点已加载且存在最终答案时可折叠 | 相同 | 相同 | 当前代码已有 | 待验收 | +| 已完成推理的收起摘要 | 只显示「思考」 | 显示首行 | 显示首行 | 当前代码已有 | 待验收 | +| 模式切换时保留摘要 DOM | 用 CSS 隐藏摘要及分隔点 | 显示原有摘要及分隔点 | 相同 | 当前代码已有 | 待验收 | +| 推理预览的局部订阅 | `ReasoningRow` 选择自己的可见性 | 相同 | 相同 | 当前代码已有 | 待验收 | +| 折叠行引用稳定 | 回调、图标及未变化的摘要保持引用;完整 Markdown 仅在展开时挂载 | 相同 | 相同 | 当前代码已有 | 待验收 | + +三档都保留整轮折叠。`expanded` 的产品含义是取消二级过程分组,并非禁止整轮折叠,也不是自动展开每个思考或工具卡的正文。分组尚未接入时,`detailed` 与 `expanded` 的 Chat 展示相同。 + +### 不依赖分组的迁移清单 + +下表的“三档共用”表示三档都应用该行为,不表示切换档位时会改变它。 + +| 功能 | compact | detailed | expanded | 当前状态 | 迁移落点与注意事项 | +|---|---|---|---|---|---| +| 流式推理摘要 | 段落首行写完后才更新 | 相同 | 相同 | 待迁移 | 保留现有摘要 DOM 和局部订阅;配套右侧渐隐。当前仍跟随最新一行,不能标为完成。原版每次扫描全文的计算方式需要优化 | +| 工具标题中文化 | 三档共用 | 三档共用 | 三档共用 | 待迁移 | Bash/Pwsh 为「运行命令」、Grep 为「搜索文件内容」、Glob 为「查找文件」、Skill 为「加载技能」;只改 UI 字典,不改模型工具名 | +| 工具行交互视觉 | 三档共用 | 三档共用 | 三档共用 | 待迁移 | 悬停时标题和摘要加深,展开箭头朝上;共享 `DisclosureRow` 的调用方一并核对 | +| Bash 停止状态的读屏提示 | 三档共用 | 三档共用 | 三档共用 | 待迁移 | 补齐停止状态的可访问名称,不改变执行或取消语义 | +| 工具及命令运行时文字扫光 | 三档共用 | 三档共用 | 三档共用 | 待迁移 | 保留固定文本节点,以运行状态控制动画;不把新建 ReactNode 和临时回调重新引入 memo 调用链;保留减少动态效果设置 | +| 取消、失败后保持过程展开 | 三档共用 | 三档共用 | 三档共用 | 待迁移 | 已停止和失败的轮次不自动收起,也不允许手动收起;可独立于计时控件迁移 | +| 整轮状态与用时控件 | 三档共用 | 三档共用 | 三档共用 | 待迁移 | 从轮次开始显示,运行时显示用时,完成后固定时长,停止或失败显示对应状态;移除底部重复运行条。控件提前出现需要处理锚点和排序,但不需要 step-group | +| 非人工触发通知 | 三档共用 | 三档共用 | 三档共用 | 待迁移 | 用持久化 Inbox 领取记录识别唤醒输入,显示独立通知;展开查看原始内容。来源标题仅使用已记录的来源字段,不解析正文猜测身份 | +| 隐藏基础设施行 | 三档共用 | 三档共用 | 三档共用 | 待迁移 | Chat 隐藏系统提示词、普通上下文注入和 permission 命令;Session 数据及 Trajectory 保留。先保住唤醒通知,再隐藏普通上下文;可见性在节点定义处集中决定 | +| 轮次操作栏位置 | 三档共用 | 三档共用 | 三档共用 | 待迁移 | 操作栏放到轮次结束之后,反馈仍对应最后一条持久化文字回复;检查中断、重试和分支操作,不直接删除相关判定 | +| 操作栏常显条件 | 三档共用 | 三档共用 | 三档共用 | 待迁移 | 最新轮仅在最后可见内容为回复时常显,其余通过悬停或键盘聚焦显示;把判定放回 Turn 自己的投影,不引入原版分组索引 | + +开发者工具默认开启已由当前基线提供,不重复迁移。当前实现保留等待 Host 接受设置后才启用相关能力的保护,不以原 PR 的缺值回退覆盖它。原 PR 的 `Switch` 改动只有注释,不作为功能迁移项。 + +### 分组阶段保留的需求 + +这些项目当前均未接入 `feat/chat-presentation-channel`。隔壁 worktree 有实验代码,不代表这些产品行为或性能要求已经完成。 + +| 功能 | compact | detailed | expanded | 当前状态 | +|---|---|---|---|---| +| 回复之间的连续过程分组 | 工具与推理归组,默认收起 | 相同 | 过程行直接展示,不使用二级分组包装 | 分组阶段 | +| 同一 Assistant 中推理与回复的分别显隐 | 推理可归入前组,回复外露 | 相同 | 不做二级分组隐藏 | 分组阶段;不直接复制原版拆成两个渲染节点的实现 | +| 组头类别摘要 | 运行时显示当前类别,完成后聚合主要类别 | 相同 | 无组头 | 分组阶段 | +| 运行中组头详情 | 不显示 | 显示命令、路径、查询等详情,无运行工具时显示推理摘要 | 无组头 | 分组阶段 | +| 组头内容更新节奏 | 保留类别标题的最短展示时间 | 同时处理详情更新 | 不适用 | 分组阶段 | +| 组内限高滚动 | 展开内容限高、独立滚动、边缘渐隐 | 相同 | 不适用 | 分组阶段 | +| 分组与整轮折叠联动 | 整轮收起时隐藏分组 | 相同 | 仅整轮折叠 | 分组阶段;保留节点身份,内部开合状态是否重置单独确定 | +| 分页、流式结算与组身份 | 既有组头和成员稳定,半截轮单独处理 | 相同 | 同一批业务节点直接展示 | 分组阶段 | + +分组产品细节的核对项:完成摘要最多聚合前三类,超过三类使用「等」;调用计数用于分类排序,不直接显示为组头数字。详细模式的实时详情合并空白并限制为 160 个字符;标题最短展示时间为 150ms,只保留最新更新,不补播积压项。展开区高度不超过 400px 与半屏中的较小值,可滚动方向显示 24px 渐隐,并保留与外层滚动的衔接。重试行不属于二级过程组。这些数值是原 PR 的行为参考,不代表当前分组实验已经实现。 + +## 性能约束 + +| 场景 | 要保留的性质 | 所需证据 | +|---|---|---| +| 切换三档模式 | 不改变业务节点 key,不因模式切换重新注册 Definition;仅相关可见性或展示字段更新 | 节点身份和刷新范围检查 | +| 推理或工具内容增量更新 | 只更新所属节点;避免每个分片重新扫描完整推理或完整历史 | 增量工作量与长内容场景 | +| 整轮运行时钟 | 只有运行中的时钟内容按秒更新,不带动整轮成员、历史行和列表 | 更新范围及计时器释放检查 | +| 摘要显隐 | 轻量摘要常驻;完整 Markdown 正文不为模式切换而全部常驻 | DOM 身份、首次加载和内存观察 | +| 分页 | 新增节点与事实变化的节点更新,已完成轮次不因全局分页状态一起刷新 | 多页历史交互与刷新范围检查 | +| 状态切换 | 文字、图标、回调引用在内容未变时稳定;不通过重挂载清空内部状态 | 交互状态与组件生命周期检查 | + +保留 DOM 只减少挂载和卸载成本,不消除样式计算、布局与绘制,也会增加常驻内存。不能将“只改显示属性”写成“不会卡顿”的保证。性能目标是降低切换峰值,并保持首次加载、分页和流式更新的成本可接受。 + +## 备选方案与取舍 + +**整批重放原 PR。** 不采用。分组、节点拆分、整轮状态和独立视觉功能混在一起,难以把性能变化对应到具体功能,也会覆盖当前通道已完成的局部订阅与节点复用。 + +**切换模式时卸载、重新创建摘要或过程节点。** 摘要模式切换不采用该方式。稳定挂载让来回切换只改变显示状态;新增节点的初始成本仍须单独检查。 + +**为了切换平滑,把所有 Markdown 正文常驻。** 不采用。轻量摘要与完整正文的内存、DOM 和渲染成本不同;正文继续按手动展开状态挂载。 + +**收起整轮时重挂载 renderer,以重置工具卡。** 不直接迁移。该实现与稳定节点及保留交互状态的方向冲突;若后续仍需要重置行为,应明确状态所有者和触发规则。 + +## 验收标准 + +完成一项时更新它的实现状态、实际落点和验证记录;未完成项保留,不因拆分分支而删除。分组阶段开始前,逐行复核上面的产品需求和模式对应关系。 + +| 验收项 | 当前状态 | +|---|---| +| 当前通道已有能力的完整行为验证 | 待验收;既有测试包含只做类型接线、尚未调整的旧断言 | +| 非分组功能迁移 | 待迁移;本次仅创建进度记录 | +| 模式切换时的 DOM 身份和刷新范围 | 待验收;不能以 memo 或 selector 的存在代替实际证据 | +| 长会话首次打开、分页、流式输入与内存 | 待验收;原 PR 的历史测量不代表本实现 | +| 新行为的单元、浏览器与录制快照覆盖 | 待补;开发阶段不在此轮运行测试或录制 | +| 分组功能与两档差异 | 分组阶段 | + +此前通道调整有编译检查记录,但不是本次全部迁移的通过证明,也不代表当前所有测试通过。本轮未执行检查。 + +## 风险 + +- 当前 `expanded` 与 `detailed` 的展示相同;只有分组阶段完成后,两档才具备原 PR 设计的区别。 +- 整轮用时控件替换现有工具和消息计数标题,属于产品信息变化;迁移时不能只换样式而遗漏状态、可访问名称或空过程轮次。 +- 普通上下文隐藏若先于触发通知,会让后台唤醒原因消失;两项需按清单顺序衔接。 +- 原 PR 的页脚判定与分组索引耦合,需要按功能重写归属,不能为页脚单独引入整套分组基础设施。 +- 分组实验中的组身份、成员归属和 builder 物化路线仍需继续评估;本记录不将实验实现列为最终架构。 diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index 7d9e60da65..489c1e8723 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-chat/README.md -README.md: eea8eeda01c3d0bd30669cdf3743c64be0d76fbe -README.zh.md: 58fef8e8c47ae5f67c8ecbf614a36bbfbf2e20b3 +README.md: 3a0e74332a0ee2c5453a024f1ffe9dfbb9ae0163 +README.zh.md: 89a385a61f08efa86c98d59fd4271f99c3b25210 diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md index eea8eeda01..3a0e74332a 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -67,6 +67,8 @@ The completed-turn action footer starts 20px below the preceding prose or extens Each reasoning row starts collapsed, including during streaming and in reasoning-only replies. Clicking the row opens or closes its complete Markdown; incoming answer text, Tool calls, and stream completion preserve that choice. Expanded reasoning uses compact secondary typography: headings add bold weight without changing text size, line height, or color. The collapsed summary stays on one line, follows the latest reasoning line while streaming, and shows the first line after settlement. +Reasoning rows retain the disclosure's callback, icon, and unchanged content references. Each reasoning row selects its preview visibility from the display policy; mode changes toggle CSS display without unmounting the collapsed summary or updating its parent Assistant renderer. Full Markdown elements are created only while expanded. + Settings → General exposes a persisted, localized `Normal` / `Compact` conversation-display preference in the `ui-chat` namespace; `Compact` is the default. Normal leaves process rows visible and renders no Turn-process control. In Compact mode, the System prompt remains independently visible before the opening User throughout the Turn. Context injection, reasoning, Assistant material, Tool rows, and Retry rows remain expanded while a Turn is open. At `turn/end`, its latest Step becomes the final-answer boundary only when it contains non-blank text, an image, or an unknown visible block—and no Tool-call block; preceding Context injection, reasoning, earlier Assistant material, Tool rows, and Retry rows then collapse by default. The control reports Turn-wide durable counts for non-subagent Tool calls, reply-bearing Assistant messages before the final answer, and subagent delegation calls; zero-valued segments are omitted, the Tool and subagent figures are mutually exclusive, and neither System prompt nor Context injection contributes a count. When all three counts are zero, the process still folds and the control reads `Thought for a while`. A full-width divider below the summary separates it from the answer or expanded process rows. User and steering messages, System prompt, error, max-token, and turn-tail rows stay outside, and a closed Turn with no final answer keeps all process evidence visible. A newly available process control is inserted without changing the relative order of existing rows: opening human input precedes the control and process rows from their first projection, while System prompt remains above that input. While older history remains available through Load earlier, process controls stay absent and no members are hidden; once history is complete, every eligible closed Turn uses the collapsed default immediately. Stable Chat Node Seats keep every renderer mounted, hidden members add no flow spacing, and a closed control sits 8px above its answer only when no independent input intervenes. Completion collapse does not depend on tail-follow position, so a reader above the tail may see the transcript reflow. An automatic collapse that would hide keyboard focus keeps the group open and leaves focus in place; a manual close focuses the process control before hiding its members. The session-scoped store records only manually expanded Turn-and-answer-Step generations; a different answer generation starts collapsed. ----- diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index 58fef8e8c4..89a385a61f 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -67,6 +67,8 @@ Chat 在节点列表外通过一个 `MarkdownDelegateProvider` 提供文件及 H 每个思考行初始都折叠,包括流式输出期间和仅含思考的回复。点击该行可展开或收起完整 Markdown;后续回答文本、工具调用和流结束都保留用户的选择。展开的思考采用紧凑的次级排版:标题只加粗,不改变字号、行高或颜色。折叠摘要保持单行,在流式输出期间跟随最新思考行,结算后显示第一行。 +思考行保留折叠控件的回调、图标和未变化内容的引用。每个思考行从展示策略中选择预览可见性;模式切换只改变 CSS 显示状态,不卸载折叠摘要,也不更新其父级 Assistant 渲染器。完整 Markdown 元素仅在展开时创建。 + 「设置 → 通用设置」提供持久化到 `ui-chat` 命名空间的「标准」/「紧凑」对话显示偏好,默认使用「紧凑」。标准模式保持所有过程行可见且不渲染轮次过程控件。紧凑模式下,系统提示词在整个轮次中始终独立显示于开场 User 上方。轮次打开期间,上下文注入、推理、Assistant 内容、工具行与重试行始终展开。到 `turn/end` 时,最后一个步骤只有在包含非空文本、图片或未知可见块且不含工具调用块时才成为最终答案边界;边界之前的上下文注入、推理、较早 Assistant 内容、工具行与重试行随后默认收起。控件展示覆盖整个轮次的非 subagent 工具调用数、最终答案之前带回复内容的 Assistant 消息数和 subagent 委派数;值为 0 的分段省略,工具调用与 subagent 两项互斥,系统提示词与上下文注入都不增加计数。三项全为 0 时过程仍会收起,控件标题显示「已思考」(英文为 `Thought for a while`)。摘要下方的通栏分隔线将其与正文或展开后的过程行隔开。用户与 steering 消息、系统提示词、错误、最大 token 与 turn-tail 行留在过程组外;关闭时没有最终答案的轮次保留全部过程证据。新的过程控件插入时不会改变既有行的相对顺序:开场人工输入从首次投影起便位于控件和过程行之前,系统提示词则始终位于该输入上方。只要仍可通过「加载更早」获取历史,过程控件就不出现,也不会隐藏任何成员;历史加载完整后,每个合格的已关闭轮次立即使用默认收起状态。稳定 Chat Node Seat 会让每个 renderer 保持挂载,隐藏成员不产生消息流间距;只有中间没有独立输入时,收起控件才与正文相隔 8px。完成后的收起不依赖是否跟随尾部,因此正在上方阅读的用户可能看到 transcript 重排。若自动收起会隐藏当前键盘焦点,则过程组保持展开且焦点留在原处;手动收起会先把焦点移到过程控件,再隐藏成员。会话作用域存储只记录用户手动展开的「轮次 + 正文步骤」generation;不同正文 generation 默认收起。 ----- diff --git a/packages/client/ui-chat/src/chat-settings.ts b/packages/client/ui-chat/src/chat-settings.ts index 021a2b0616..ccc9bc55fd 100644 --- a/packages/client/ui-chat/src/chat-settings.ts +++ b/packages/client/ui-chat/src/chat-settings.ts @@ -5,15 +5,24 @@ import z from '@deepseek-ai/schemastery' /** Settings namespace owned by the Chat target. */ export const CHAT_SETTINGS_NAMESPACE = 'ui-chat' -/** Field carrying the completed-Turn transcript presentation mode. */ +/** Field carrying the work-details presentation mode. */ export const TRANSCRIPT_VIEW_FIELD = 'transcriptView' -/** Transcript presentation modes accepted at settings boundaries. */ -export const TRANSCRIPT_VIEW_MODES = ['normal', 'compact'] as const +/** Work-details presentation modes a user can choose. */ +export const TRANSCRIPT_VIEW_MODES = ['compact', 'detailed', 'expanded'] as const -/** Completed-Turn transcript presentation. */ +/** Work-details presentation mode. */ export type TranscriptViewMode = typeof TRANSCRIPT_VIEW_MODES[number] +/** + * Saved value from the two-mode generation of this setting. Read as `detailed`; + * never offered as a choice and never written back. + */ +export const LEGACY_TRANSCRIPT_VIEW_MODE = 'normal' + +/** Every value the durable field accepts: current modes plus the legacy saved value. */ +const TRANSCRIPT_VIEW_SETTING_VALUES = [...TRANSCRIPT_VIEW_MODES, LEGACY_TRANSCRIPT_VIEW_MODE] as const + /** Default preserves the compact process disclosure introduced by Chat. */ export const DEFAULT_TRANSCRIPT_VIEW_MODE: TranscriptViewMode = 'compact' @@ -34,8 +43,8 @@ export const DEFAULT_LINK_OPENING: LinkOpening = 'sidebar' /** Durable Chat section shared by the Host schema and browser scope. */ export interface ChatSettings { - /** Presentation mode for completed Turn process content. */ - transcriptView: TranscriptViewMode + /** Work-details preference; the legacy value is accepted only from existing saved settings. */ + transcriptView: TranscriptViewMode | typeof LEGACY_TRANSCRIPT_VIEW_MODE /** Detail level for composer statistics and completed-Turn usage. */ performanceUsage: PerformanceUsageMode /** Default destination for Chat HTTP(S) links. */ @@ -46,5 +55,5 @@ export interface ChatSettings { export const ChatSettingsSchema: z = z.object({ linkOpening: z.union(['sidebar', 'new-tab']).default(DEFAULT_LINK_OPENING), performanceUsage: z.union([...PERFORMANCE_USAGE_MODES]).default(DEFAULT_PERFORMANCE_USAGE), - [TRANSCRIPT_VIEW_FIELD]: z.union([...TRANSCRIPT_VIEW_MODES]).default(DEFAULT_TRANSCRIPT_VIEW_MODE), + [TRANSCRIPT_VIEW_FIELD]: z.union([...TRANSCRIPT_VIEW_SETTING_VALUES]).default(DEFAULT_TRANSCRIPT_VIEW_MODE), }) diff --git a/packages/client/ui-chat/src/client/apply.ts b/packages/client/ui-chat/src/client/apply.ts index 079a5e2512..70390ec889 100644 --- a/packages/client/ui-chat/src/client/apply.ts +++ b/packages/client/ui-chat/src/client/apply.ts @@ -34,6 +34,7 @@ import { en, NS, zh } from './locale.ts' import { TranscriptViewRow, type TranscriptViewRowInjected } from './settings/TranscriptViewRow.tsx' import { createChatStore } from './stores.ts' import { TranscriptViewPolicy } from './transcript-view.ts' +import { derivePresentationPolicy } from './presentation-policy.ts' import { CHAT_SETTINGS_NAMESPACE, DEFAULT_LINK_OPENING, type ChatSettings } from '../chat-settings.ts' import { LinkOpeningRow, type LinkOpeningRowInjected } from './settings/LinkOpeningRow.tsx' import { PerformanceUsageRow, type PerformanceUsageRowInjected } from './settings/PerformanceUsageRow.tsx' @@ -111,9 +112,10 @@ export function apply(ctx: Context): void { }, LinkOpeningRow)) }) const transcriptView = new TranscriptViewPolicy(chatSettings) + const presentation = derivePresentationPolicy(transcriptView.mode) const performancePolicy = new PerformanceUsagePolicy(chatSettings) const performanceUsage = performancePolicy.mode - registerChatNodeRenderers(ctx, performanceUsage) + registerChatNodeRenderers(ctx, performanceUsage, presentation) ctx.slots.inject('settings.general.item', () => ctx.slots.register({ name: 'settings.general.item', @@ -155,7 +157,7 @@ export function apply(ctx: Context): void { const session = binding.session const chat = chatSource(binding) return { - hooks: { transcriptView: transcriptView.mode }, + hooks: { presentation }, keyedHooks: { chatNode: key => chat.getSnapshot().nodes.source(key), chatNodeProcess: key => chat.getSnapshot().nodes.processSource(key), diff --git a/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx b/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx index 13ff7fae4b..967a7a09b1 100644 --- a/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx +++ b/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx @@ -2,7 +2,7 @@ import { Fragment, memo, useMemo } from 'react' import type { ReactNode } from 'react' import { JsonBlock, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives' import type { MarkdownFileMentions, MarkdownPathImages } from '@deepseek-ai/dsh-client-ui-primitives' -import type { ChatNodeOwnerProps, ChatViewSlotProps } from '../contract/slots.ts' +import type { ChatNodeOwnerProps, ChatViewSlotProps, UsePresentation } from '../contract/slots.ts' import type { AssistantBlock } from '../contract/snapshot.ts' import { markdownLabels } from '../markdown-labels.ts' import { ReasoningRow } from './ReasoningRow.tsx' @@ -29,9 +29,11 @@ export interface AssistantMarkdownProps { interrupted?: boolean | undefined /** Render consecutive image blocks through the attachment slot. */ renderMessageImages: ChatNodeOwnerProps['renderMessageImages'] - /** Hide reasoning that belongs to the Turn-level process disclosure. */ + /** Hide reasoning that belongs to the Turn-level process disclosure or a collapsed step group. */ reasoningHidden?: boolean | undefined - /** Reveal the owning Turn-level process disclosure. */ + /** Live display policy for reasoning summaries. */ + usePresentation: UsePresentation + /** Reveal the disclosure that hides this reasoning. */ revealProcess?: (() => void) | undefined /** Resolved prose file mentions for this Assistant's closing turn. */ mentions?: MarkdownFileMentions | undefined @@ -42,7 +44,7 @@ export interface AssistantMarkdownProps { /** Reasoning block as the Think variant summary row (figma 39:28304). */ export const AssistantMarkdown = memo(function AssistantMarkdown({ blocks, streaming, interrupted, renderMessageImages, - reasoningHidden = false, revealProcess, mentions, t, + reasoningHidden = false, usePresentation, revealProcess, mentions, t, }: AssistantMarkdownProps) { // Stable per locale revision (t identity changes on switch): a fresh object // per render would rebuild MarkdownText's component table every chunk. @@ -83,7 +85,7 @@ export const AssistantMarkdown = memo(function AssistantMarkdown({ hidden={reasoningHidden} reveal={revealProcess} > - + , ) break diff --git a/packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx b/packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx index 399897a9b5..9ef72941f5 100644 --- a/packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx +++ b/packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx @@ -1,11 +1,14 @@ import { memo, useCallback, useMemo } from 'react' -import type { ChatNodeViewProps, TurnTailOwnerProps } from '../contract/slots.ts' +import type { InjectFace } from '@deepseek-ai/dsh-client-ui-slots' +import type { ChatNodeViewProps, PresentationInjected, TurnTailOwnerProps } from '../contract/slots.ts' import { AssistantMarkdown } from './AssistantMarkdown.tsx' +type AssistantNodeViewProps = ChatNodeViewProps<'assistant-step'> & InjectFace + /** Streaming, settled, and interrupted Assistant states share one keyed renderer instance. */ export const AssistantNodeView = memo(function AssistantNodeView({ - node, useTurnData, turnProcess, openFile, renderMessageImages, fileMentions, t, -}: ChatNodeViewProps<'assistant-step'>) { + node, useTurnData, turnProcess, openFile, renderMessageImages, fileMentions, usePresentation, t, +}: AssistantNodeViewProps) { const data = node.data const turn = node.location.kind === 'turn' || node.location.kind === 'step' ? node.location.turn @@ -33,6 +36,7 @@ export const AssistantNodeView = memo(function AssistantNodeView({ interrupted={data.status === 'interrupted'} renderMessageImages={renderMessageImages} reasoningHidden={reasoningHidden} + usePresentation={usePresentation} revealProcess={revealProcess} mentions={mentions} t={t} diff --git a/packages/client/ui-chat/src/client/chat/ChatNodeSeat.tsx b/packages/client/ui-chat/src/client/chat/ChatNodeSeat.tsx index 40e08dbaf7..3ed6f7b8d8 100644 --- a/packages/client/ui-chat/src/client/chat/ChatNodeSeat.tsx +++ b/packages/client/ui-chat/src/client/chat/ChatNodeSeat.tsx @@ -1,7 +1,7 @@ import { memo, useCallback, useMemo } from 'react' import { JsonBlock } from '@deepseek-ai/dsh-client-ui-primitives' import type { ConversationLocationDataStore, ConversationTurnDataMap } from '@deepseek-ai/dsh-client-ui-conversation/client' -import type { ChatNodeOwnerProps, ChatViewSlotProps } from '../contract/slots.ts' +import type { ChatNodeOwnerProps, ChatViewSlotProps, UsePresentation } from '../contract/slots.ts' import type { ChatNode } from '../contract/chat-nodes.ts' import { TURN_PROCESS_INDEPENDENT_KINDS } from '../contract/turn-process.ts' import { storedTurnProcessEntry } from '../stores.ts' @@ -12,8 +12,7 @@ interface ChatNodeSeatProps extends ChatNodeOwnerProps { readonly nodeKey: string readonly useChatNode: ChatViewSlotProps['useChatNode'] readonly useChatNodeProcess: ChatViewSlotProps['useChatNodeProcess'] - readonly historyIncomplete: boolean - readonly compactTranscript: boolean + readonly usePresentation: UsePresentation readonly useStore: ChatViewSlotProps['useStore'] readonly actions: ChatViewSlotProps['actions'] readonly renderSlot: ChatViewSlotProps['renderSlot'] @@ -34,9 +33,13 @@ function turnOf(node: ChatNode | undefined): number | undefined { return location?.kind === 'turn' || location?.kind === 'step' ? location.turn.turn : undefined } -/** Subscribe, apply Turn-process visibility, and dispatch one stable Context key. */ +/** + * Subscribe, apply Turn-process visibility, and dispatch one stable Context key. + * Policy reads select this seat's own conclusion, so a mode change re-renders + * only seats whose visibility actually changes. + */ export const ChatNodeSeat = memo(function ChatNodeSeat({ - nodeKey, useChatNode, useChatNodeProcess, historyIncomplete, compactTranscript, + nodeKey, useChatNode, useChatNodeProcess, usePresentation, cwd, openFile, openSkill, inspectCall, forkAt, loadImage, renderMessageImages, fileMentions, useStore, actions, renderSlot, t, }: ChatNodeSeatProps) { @@ -59,13 +62,15 @@ export const ChatNodeSeat = memo(function ChatNodeSeat({ actions.setTurnProcessOpen(processSpec.turn, processSpec.answerStep, open) } }, [actions, processSpec]) + const foldCompleted = usePresentation(policy => policy.foldCompletedTurns) + // Folding is decided per Turn: the Turn is closed and its start is loaded. const processWindowReady = processSpec !== undefined && processPresentation !== undefined - && compactTranscript + && foldCompleted && processSpec.answerAnchorSeq !== null && processPresentation.turn === processSpec.turn && processPresentation.turnClosed - && !historyIncomplete + && processPresentation.turnStarted const processMember = routedNode !== undefined && processWindowReady && !TURN_PROCESS_INDEPENDENT_KINDS.has(routedNode.kind) diff --git a/packages/client/ui-chat/src/client/chat/ChatView.tsx b/packages/client/ui-chat/src/client/chat/ChatView.tsx index 257dad64ab..bad68eb828 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.tsx +++ b/packages/client/ui-chat/src/client/chat/ChatView.tsx @@ -113,7 +113,7 @@ const ChatNodeList = memo(function ChatNodeList({ order, ...seatProps }: ChatNod export function ChatView({ useSession, useChat, useChatNode, useChatNodeProcess, useSessions, useStore, actions, renderSlot, sessionId, openFile, openSkill, openExternalLink, loadOlder, loadThrough, loadImage, inspectCall, chatScroll, forkAt, fileMentions, - useTranscriptView, useProjection, t, + usePresentation, useProjection, t, }: ChatViewSlotProps) { const order = useChat(s => s.order) const nodeStore = useChat(s => s.nodes) @@ -137,7 +137,6 @@ export function ChatView({ const openError = useSession(s => s.openError) const hasMore = useSession(s => s.hasMore) const loadingOlder = useSession(s => s.loadingOlder) - const compactTranscript = useTranscriptView(mode => mode === 'compact') const [fileOpenError, setFileOpenError] = useState<{ path: string; message: string } | null>(null) const [fileOpenBusy, setFileOpenBusy] = useState(false) // Close/retry must ignore a settlement that started before the latest @@ -237,8 +236,7 @@ export function ChatView({ order={order} useChatNode={useChatNode} useChatNodeProcess={useChatNodeProcess} - historyIncomplete={hasMore} - compactTranscript={compactTranscript} + usePresentation={usePresentation} useStore={useStore} actions={actions} cwd={cwd} diff --git a/packages/client/ui-chat/src/client/chat/ReasoningRow.module.css b/packages/client/ui-chat/src/client/chat/ReasoningRow.module.css index 3ca51f8d85..5e98217171 100644 --- a/packages/client/ui-chat/src/client/chat/ReasoningRow.module.css +++ b/packages/client/ui-chat/src/client/chat/ReasoningRow.module.css @@ -97,6 +97,11 @@ text-overflow: clip; } +.root:not([data-preview]) .separator, +.root:not([data-preview]) .summary { + display: none; +} + .thinkBody { /* Indent under the title, which starts at leading (16 + delta) + gap 6. */ padding: 4px 0 4px calc(22px + var(--dsh-content-font-delta, 0px)); diff --git a/packages/client/ui-chat/src/client/chat/ReasoningRow.tsx b/packages/client/ui-chat/src/client/chat/ReasoningRow.tsx index 4d484af95b..2d01eeb7fd 100644 --- a/packages/client/ui-chat/src/client/chat/ReasoningRow.tsx +++ b/packages/client/ui-chat/src/client/chat/ReasoningRow.tsx @@ -1,11 +1,13 @@ /** Assistant reasoning disclosure, independent of Tool-call presentation. */ -import { useMemo, useState } from 'react' +import { memo, useCallback, useMemo, useState } from 'react' import { DisclosureRow, IconThinkOutlineRegular, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives' -import type { ChatViewSlotProps } from '../contract/slots.ts' +import type { ChatViewSlotProps, UsePresentation } from '../contract/slots.ts' import { markdownLabels } from '../markdown-labels.ts' import a11yCss from './accessibility.module.css' import css from './ReasoningRow.module.css' +const THINK_ICON = + function firstLine(text: string): string { const newline = text.indexOf('\n') return newline === -1 ? text : text.slice(0, newline) @@ -20,16 +22,40 @@ function latestLine(text: string): string { /** * Render one assistant reasoning block collapsed until the reader opens it. The * collapsed summary omits double-asterisk markers; expanded content renders - * the complete Markdown with secondary typography. + * the complete Markdown with secondary typography. A streaming row always + * previews its latest line. Mode changes toggle CSS display without unmounting + * collapsed summaries. * @param props.text - complete or streaming reasoning text. * @param props.running - whether this block is the streaming tail. + * @param props.usePresentation - live display-policy selector for this reasoning row. * @param props.t - conversation locale seat for status and Markdown actions. * @returns the reasoning disclosure. */ -export function ReasoningRow({ text, running, t }: { text: string; running: boolean; t: ChatViewSlotProps['t'] }) { +export const ReasoningRow = memo(function ReasoningRow({ text, running, usePresentation, t }: { + text: string + running: boolean + usePresentation: UsePresentation + t: ChatViewSlotProps['t'] +}) { const [expanded, setExpanded] = useState(false) const labels = useMemo(() => markdownLabels(t), [t]) + const toggle = useCallback(() => { setExpanded(value => !value) }, []) const summary = (running ? latestLine(text) : firstLine(text)).replaceAll('**', '') + const preview = usePresentation(policy => !expanded && summary !== '' + && (running || policy.settledReasoningPreview)) + const collapsedContent = useMemo(() => ( + <> + + + {summary} + + + ), [running, summary]) + const content = useMemo(() => expanded ? ( +
+ +
+ ) : undefined, [expanded, labels, running, text]) return (
{running && {t('row.running')}} } + icon={THINK_ICON} title={t('message.think')} open={expanded} expandable expandOnRowClick - onToggle={() => { setExpanded(value => !value) }} - collapsedContent={( - <> - - - {summary} - - - )} + onToggle={toggle} + collapsedContent={collapsedContent} > -
- -
+ {content}
) -} +}) diff --git a/packages/client/ui-chat/src/client/chat/register-node-renderers.ts b/packages/client/ui-chat/src/client/chat/register-node-renderers.ts index f8f78000f1..9fa302992d 100644 --- a/packages/client/ui-chat/src/client/chat/register-node-renderers.ts +++ b/packages/client/ui-chat/src/client/chat/register-node-renderers.ts @@ -1,6 +1,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import type { PerformanceUsageMode } from '../../chat-settings.ts' +import type { ChatPresentationPolicy } from '../presentation-policy.ts' import { NS } from '../locale.ts' import { AssistantNodeView } from './AssistantNodeView.tsx' import { CommandNodeView, ManualCompactionNodeView } from './CommandNodeView.tsx' @@ -14,10 +15,17 @@ import { TurnTailNodeView } from './TurnTailNodeView.tsx' /** * Register this package's business renderers behind the keyed Chat Node seat. + * Renderers whose output depends on the work-details mode receive the policy + * through their own registration; the seat and the other renderers do not. * @param ctx - owning UI Conversation context. * @param performanceUsage - live statistics detail preference. + * @param presentation - live presentation policy. */ -export function registerChatNodeRenderers(ctx: Context, performanceUsage: ObservableSnapshot): void { +export function registerChatNodeRenderers( + ctx: Context, + performanceUsage: ObservableSnapshot, + presentation: ObservableSnapshot, +): void { ctx.slots.inject('conversation.chat.node', () => ctx.slots.register( { name: 'conversation.chat.node', key: 'user', locale: NS }, UserMessageNodeView)) ctx.slots.inject('conversation.chat.node', () => ctx.slots.register( @@ -26,8 +34,12 @@ export function registerChatNodeRenderers(ctx: Context, performanceUsage: Observ { name: 'conversation.chat.node', key: 'context', locale: NS }, ContextMessageNodeView)) ctx.slots.inject('conversation.chat.node', () => ctx.slots.register( { name: 'conversation.chat.node', key: 'system-prompt', locale: NS }, SystemPromptNodeView)) - ctx.slots.inject('conversation.chat.node', () => ctx.slots.register( - { name: 'conversation.chat.node', key: 'assistant-step', locale: NS }, AssistantNodeView)) + ctx.slots.inject('conversation.chat.node', () => ctx.slots.register({ + name: 'conversation.chat.node', + key: 'assistant-step', + locale: NS, + inject: () => ({ hooks: { presentation } }), + }, AssistantNodeView)) ctx.slots.inject('conversation.chat.node', () => ctx.slots.register({ name: 'conversation.chat.node', key: 'command', diff --git a/packages/client/ui-chat/src/client/contract/slots.ts b/packages/client/ui-chat/src/client/contract/slots.ts index 5e811b7963..4086eb4d5b 100644 --- a/packages/client/ui-chat/src/client/contract/slots.ts +++ b/packages/client/ui-chat/src/client/contract/slots.ts @@ -9,17 +9,18 @@ import type { InjectFace, KeyedSnapshotSelectorHook, PropsLocale, PropsRenderSlots, PropsRuntime, PropsStore, SlotHookFactory, SnapshotSelectorHook, } from '@deepseek-ai/dsh-client-ui-slots' -import type { ObservableSnapshot, SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import type { MarkdownFileMentions } from '@deepseek-ai/dsh-client-ui-primitives' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type { createChatStore } from '../stores.ts' +import type { ChatPresentationPolicy } from '../presentation-policy.ts' import type { ToolCallId } from './store.ts' import type { ChatConversationViewNode, ChatNode, ChatNodeKind } from './chat-nodes.ts' import type { ChatNodeProcessSource, ChatNodeSource, ChatSnapshot, ChatTurnProcessPresentation, } from './snapshot.ts' import type { TurnProcessSpec } from './turn-process.ts' -import type { PerformanceUsageMode, TranscriptViewMode } from '../../chat-settings.ts' +import type { PerformanceUsageMode } from '../../chat-settings.ts' /** Selector hook over the current Conversation binding's Chat target. */ export type UseChat = SnapshotSelectorHook @@ -30,6 +31,13 @@ export type UseChatNode = KeyedSnapshotSelectorHook +/** + * Selector hook over the live presentation policy. Callers select one field or + * a derived conclusion, never the whole policy, so a mode change re-renders + * only components whose selected value changed. + */ +export type UsePresentation = SnapshotSelectorHook + /** Where in a file an open should land. */ export interface OpenFileOptions { /** 1-based line to reveal; absent = the file's beginning. */ @@ -105,6 +113,14 @@ export interface TurnProcessOwnerProps { setOpen(open: boolean): void } +/** Shared presentation policy source for renderers that depend on the work-details mode. */ +export interface PresentationInjected { + hooks: { + /** Live presentation policy derived from the accepted work-details mode. */ + presentation: ObservableSnapshot + } +} + /** Full props of one keyed Chat renderer. */ export type ChatNodeViewProps = PropsRuntime<'conversation.chat.node', Kind> & PropsLocale<'chat'> @@ -139,8 +155,8 @@ export interface PerformanceUsageInjected { /** Business callbacks injected into the Chat view. */ export interface ChatViewInjected { hooks: { - /** Persisted completed-Turn transcript presentation. */ - transcriptView: SnapshotStore + /** Live presentation policy derived from the accepted work-details mode. */ + presentation: ObservableSnapshot } keyedHooks: { /** Resolve the stable source for one Chat Node key. */ diff --git a/packages/client/ui-chat/src/client/contract/snapshot.ts b/packages/client/ui-chat/src/client/contract/snapshot.ts index 80f8654e7c..86833382c0 100644 --- a/packages/client/ui-chat/src/client/contract/snapshot.ts +++ b/packages/client/ui-chat/src/client/contract/snapshot.ts @@ -74,6 +74,8 @@ export interface ChatLocationNodeIndex { export interface ChatTurnProcessPresentation { readonly turn: number readonly spec: TurnProcessSpec + /** Whether the loaded window contains this Turn's `turn/start`; folding is decided per Turn on this fact. */ + readonly turnStarted: boolean readonly turnClosed: boolean readonly hasExternalProcess: boolean readonly compactAnswer: boolean diff --git a/packages/client/ui-chat/src/client/conversation-nodes/turn-process-presentation.ts b/packages/client/ui-chat/src/client/conversation-nodes/turn-process-presentation.ts index a49ae6031b..98a33a6c8b 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/turn-process-presentation.ts +++ b/packages/client/ui-chat/src/client/conversation-nodes/turn-process-presentation.ts @@ -16,6 +16,7 @@ function samePresentation( return left === right || (left !== undefined && right !== undefined && left.spec === right.spec && left.turn === right.turn + && left.turnStarted === right.turnStarted && left.turnClosed === right.turnClosed && left.hasExternalProcess === right.hasExternalProcess && left.compactAnswer === right.compactAnswer) @@ -64,6 +65,7 @@ function derivePresentation( return { turn, spec, + turnStarted: location.turn.start !== undefined, turnClosed: location.turn.status === 'closed', hasExternalProcess, compactAnswer, diff --git a/packages/client/ui-chat/src/client/index.ts b/packages/client/ui-chat/src/client/index.ts index 9c2fe3a5d0..6bef23a2c5 100644 --- a/packages/client/ui-chat/src/client/index.ts +++ b/packages/client/ui-chat/src/client/index.ts @@ -30,11 +30,13 @@ export type { export type { ChatStoreState, ToolCallId, TurnProcessViewEntry } from './contract/store.ts' export type { TranscriptViewRowInjected, TranscriptViewRowProps } from './settings/TranscriptViewRow.tsx' export type { TranscriptViewMode } from '../chat-settings.ts' +export type { ChatPresentationPolicy } from './presentation-policy.ts' +export { derivePresentationPolicy, presentationPolicyFor } from './presentation-policy.ts' export type { AssistantActionOwnerProps, ChatFileMentions, ChatNodeOwnerProps, ChatNodeTurnDataInjected, ChatNodeViewProps, ChatScrollPosition, ChatStore, ChatViewInjected, ChatViewSlotProps, - CommandRowOwnerProps, CommandRowProps, MessageImagesProps, OpenFileOptions, - TurnProcessOwnerProps, TurnTailOwnerProps, UseChat, UseChatNodeTurnData, + CommandRowOwnerProps, CommandRowProps, MessageImagesProps, OpenFileOptions, PresentationInjected, + TurnProcessOwnerProps, TurnTailOwnerProps, UseChat, UseChatNodeTurnData, UsePresentation, } from './contract/slots.ts' export type { TurnProcessSpec, diff --git a/packages/client/ui-chat/src/client/locale.ts b/packages/client/ui-chat/src/client/locale.ts index 51d3adca00..a0440b4682 100644 --- a/packages/client/ui-chat/src/client/locale.ts +++ b/packages/client/ui-chat/src/client/locale.ts @@ -35,10 +35,11 @@ export const zh = { 'settings.links.description': '选择聊天中 HTTP(S) 链接的打开位置', 'settings.links.sidebar': '内置浏览器', 'settings.links.newTab': '浏览器新标签页', - 'settings.transcript.title': '对话显示', - 'settings.transcript.description': '控制已完成轮次的过程内容', - 'settings.transcript.normal': '标准', - 'settings.transcript.compact': '紧凑', + 'settings.transcript.title': '工作过程展示', + 'settings.transcript.description': '控制轮次和步骤的默认展开方式', + 'settings.transcript.compact': '简洁', + 'settings.transcript.detailed': '详细', + 'settings.transcript.expanded': '完全展开', 'fileOpen.title': '无法打开文件', 'fileOpen.unknown': '无法打开此文件', 'message.extraBlock': '附加内容块', @@ -149,10 +150,11 @@ export const en = { 'settings.links.description': 'Choose where HTTP(S) links in chat open', 'settings.links.sidebar': 'Built-in browser', 'settings.links.newTab': 'New browser tab', - 'settings.transcript.title': 'Conversation display', - 'settings.transcript.description': 'Controls process content in completed turns', - 'settings.transcript.normal': 'Normal', + 'settings.transcript.title': 'Work details', + 'settings.transcript.description': 'Controls how turns and steps expand by default', 'settings.transcript.compact': 'Compact', + 'settings.transcript.detailed': 'Detailed', + 'settings.transcript.expanded': 'Expanded', 'fileOpen.title': 'Couldn’t open file', 'fileOpen.unknown': 'Couldn’t open this file', 'message.extraBlock': 'Extra content block', diff --git a/packages/client/ui-chat/src/client/presentation-policy.ts b/packages/client/ui-chat/src/client/presentation-policy.ts new file mode 100644 index 0000000000..9221afa711 --- /dev/null +++ b/packages/client/ui-chat/src/client/presentation-policy.ts @@ -0,0 +1,70 @@ +/** + * Runtime vocabulary derived from the persisted work-details mode. Renderers + * and seats select single fields of this policy; none of them compares the + * mode enum, so adding a mode changes only the table below. + */ + +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { TranscriptViewMode } from '../chat-settings.ts' + +/** Presentation capabilities that one work-details mode enables. */ +export interface ChatPresentationPolicy { + /** Mode this policy was derived from; for diagnostics, never for branching in renderers. */ + readonly mode: TranscriptViewMode + /** Whether a normally completed Turn folds its process rows behind the whole-Turn control. */ + readonly foldCompletedTurns: boolean + /** + * How consecutive process rows between Assistant replies present: `collapsed` + * groups them behind a step-group row that starts closed; `none` renders + * every row directly under the whole-Turn control with no group rows. + */ + readonly stepGrouping: 'collapsed' | 'none' + /** Whether a settled reasoning row previews its first line beside the Think title. */ + readonly settledReasoningPreview: boolean +} + +const POLICIES: Readonly> = { + compact: { + mode: 'compact', + foldCompletedTurns: true, + stepGrouping: 'collapsed', + settledReasoningPreview: false, + }, + detailed: { + mode: 'detailed', + foldCompletedTurns: true, + stepGrouping: 'collapsed', + settledReasoningPreview: true, + }, + expanded: { + mode: 'expanded', + foldCompletedTurns: true, + stepGrouping: 'none', + settledReasoningPreview: true, + }, +} + +/** + * Resolve the policy constant for one mode. The same mode always yields the + * same object, so selectors over a policy see stable identities. + * @param mode - persisted work-details mode. + * @returns the mode's presentation policy. + */ +export function presentationPolicyFor(mode: TranscriptViewMode): ChatPresentationPolicy { + return POLICIES[mode] +} + +/** + * Derive a policy observable from the mode observable without a subscription of + * its own: reads are a table lookup and change notifications are the mode's. + * @param mode - live work-details mode. + * @returns observable policy that changes exactly when the mode changes. + */ +export function derivePresentationPolicy( + mode: ObservableSnapshot, +): ObservableSnapshot { + return { + getSnapshot: () => POLICIES[mode.getSnapshot()], + subscribe: listener => mode.subscribe(listener), + } +} diff --git a/packages/client/ui-chat/src/client/settings/TranscriptViewRow.tsx b/packages/client/ui-chat/src/client/settings/TranscriptViewRow.tsx index 7dc7df7363..2b29abacd9 100644 --- a/packages/client/ui-chat/src/client/settings/TranscriptViewRow.tsx +++ b/packages/client/ui-chat/src/client/settings/TranscriptViewRow.tsx @@ -1,18 +1,18 @@ -/** General Settings row for completed-Turn transcript presentation. */ +/** General Settings row for work-details presentation. */ import type { SnapshotStore } from '@deepseek-ai/dsh-client-store' import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' -import type { TranscriptViewMode } from '../../chat-settings.ts' +import { TRANSCRIPT_VIEW_MODES, type TranscriptViewMode } from '../../chat-settings.ts' import type { ChatKey } from '../locale.ts' import { PreferenceRow } from './PreferenceRow.tsx' -/** Registration-side transcript preference face. */ +/** Registration-side work-details preference face. */ export interface TranscriptViewRowInjected { hooks: { - /** Persisted transcript preference bound as useTranscriptView. */ + /** Persisted work-details preference bound as useTranscriptView. */ transcriptView: SnapshotStore } - /** Change the completed-Turn transcript presentation. */ + /** Change the work-details presentation. */ setTranscriptView: (mode: TranscriptViewMode) => void } @@ -22,28 +22,26 @@ export type TranscriptViewRowProps = & PropsLocale<'chat'> & InjectFace -const OPTIONS: readonly { id: TranscriptViewMode; label: ChatKey }[] = [ - { id: 'normal', label: 'settings.transcript.normal' }, - { id: 'compact', label: 'settings.transcript.compact' }, -] +const LABELS = { + compact: 'settings.transcript.compact', + detailed: 'settings.transcript.detailed', + expanded: 'settings.transcript.expanded', +} as const satisfies Record /** - * Render the completed-Turn transcript mode selector. + * Render the work-details mode selector. * @param props - composed Settings slot props. * @returns the preference row. */ export function TranscriptViewRow({ useTranscriptView, setTranscriptView, t }: TranscriptViewRowProps) { const mode = useTranscriptView(value => value) - const selectedLabel = mode === 'normal' - ? 'settings.transcript.normal' - : 'settings.transcript.compact' return ( ({ id: option.id, label: t(option.label) }))} + selectedLabel={t(LABELS[mode])} + options={TRANSCRIPT_VIEW_MODES.map(id => ({ id, label: t(LABELS[id]) }))} onSelect={(value) => { setTranscriptView(value as TranscriptViewMode) }} /> ) diff --git a/packages/client/ui-chat/src/client/transcript-view.ts b/packages/client/ui-chat/src/client/transcript-view.ts index 5534a0139c..a97e17bda8 100644 --- a/packages/client/ui-chat/src/client/transcript-view.ts +++ b/packages/client/ui-chat/src/client/transcript-view.ts @@ -1,13 +1,13 @@ -/** Host-backed completed-Turn transcript presentation policy. */ +/** Host-backed work-details presentation policy. */ import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' import type { SettingsScope } from '@deepseek-ai/dsh-client-ui-settings/client' import { - DEFAULT_TRANSCRIPT_VIEW_MODE, TRANSCRIPT_VIEW_FIELD, + DEFAULT_TRANSCRIPT_VIEW_MODE, LEGACY_TRANSCRIPT_VIEW_MODE, TRANSCRIPT_VIEW_FIELD, type ChatSettings, type TranscriptViewMode, } from '../chat-settings.ts' -/** Live transcript preference consumed by Chat and its Settings row. */ +/** Live work-details preference consumed by Chat and its Settings row. */ export class TranscriptViewPolicy { /** Reactive current mode; defaults to Compact before Host settings arrive. */ readonly mode: SnapshotStore = createSnapshotStore(DEFAULT_TRANSCRIPT_VIEW_MODE) @@ -22,7 +22,7 @@ export class TranscriptViewPolicy { /** * Publish and persist one explicit user choice. - * @param mode - Normal or Compact transcript presentation. + * @param mode - Compact, Detailed, or Expanded work details. */ setMode(mode: TranscriptViewMode): void { if (this.mode.getSnapshot() === mode) return @@ -33,7 +33,8 @@ export class TranscriptViewPolicy { /** Adopt the latest accepted Host section without writing it back. */ private adopt(): void { const section = this.host.getSnapshot().value - if (section === undefined || this.mode.getSnapshot() === section.transcriptView) return - this.mode.set(section.transcriptView) + if (section === undefined) return + const mode = section.transcriptView === LEGACY_TRANSCRIPT_VIEW_MODE ? 'detailed' : section.transcriptView + if (this.mode.getSnapshot() !== mode) this.mode.set(mode) } } diff --git a/packages/client/ui-chat/src/index.ts b/packages/client/ui-chat/src/index.ts index 6229537c23..cd0c89e5c5 100644 --- a/packages/client/ui-chat/src/index.ts +++ b/packages/client/ui-chat/src/index.ts @@ -5,7 +5,7 @@ import type {} from '@deepseek-ai/dsh-settings' import { CHAT_SETTINGS_NAMESPACE, ChatSettingsSchema } from './chat-settings.ts' export { - CHAT_SETTINGS_NAMESPACE, DEFAULT_TRANSCRIPT_VIEW_MODE, TRANSCRIPT_VIEW_FIELD, + CHAT_SETTINGS_NAMESPACE, DEFAULT_TRANSCRIPT_VIEW_MODE, LEGACY_TRANSCRIPT_VIEW_MODE, TRANSCRIPT_VIEW_FIELD, TRANSCRIPT_VIEW_MODES, type ChatSettings, type TranscriptViewMode, } from './chat-settings.ts' diff --git a/packages/client/ui-chat/tests/assistant-markdown-path-images.client.spec.tsx b/packages/client/ui-chat/tests/assistant-markdown-path-images.client.spec.tsx index 55a02209ed..77bc597140 100644 --- a/packages/client/ui-chat/tests/assistant-markdown-path-images.client.spec.tsx +++ b/packages/client/ui-chat/tests/assistant-markdown-path-images.client.spec.tsx @@ -2,6 +2,7 @@ import { cleanup, render } from '@testing-library/react' import { afterEach, describe, expect, it } from 'vitest' import { AssistantMarkdown, localPathMediaUrl } from '../src/client/chat/AssistantMarkdown.tsx' +import { useDetailedPresentation } from './presentation-fixture.client.ts' import type { ChatNodeOwnerProps, ChatViewSlotProps } from '../src/client/contract/slots.ts' import type { AssistantBlock } from '../src/client/contract/snapshot.ts' @@ -54,6 +55,7 @@ describe('AssistantMarkdown local-path images', () => { it('renders a local image path in closing prose through the same-origin API', () => { const { container } = render( { it('keeps non-absolute destinations inert', () => { const { container } = render( { const face = (row.inject as unknown as () => TranscriptViewRowInjected)() expect(face.hooks.transcriptView.getSnapshot()).toBe('compact') - face.setTranscriptView('normal') - expect(face.hooks.transcriptView.getSnapshot()).toBe('normal') - expect(b.chatSettings.set).toHaveBeenCalledWith('transcriptView', 'normal') + face.setTranscriptView('detailed') + expect(face.hooks.transcriptView.getSnapshot()).toBe('detailed') + expect(b.chatSettings.set).toHaveBeenCalledWith('transcriptView', 'detailed') b.chatSettings.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'compact', performanceUsage: 'detailed' }, revision: 1, writable: true, diff --git a/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx b/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx index 013ed04786..f389653c72 100644 --- a/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx @@ -16,6 +16,7 @@ import { UserMessageNodeView, } from '../src/client/chat/MessageItem.tsx' import { AssistantMarkdown, type AssistantMarkdownProps } from '../src/client/chat/AssistantMarkdown.tsx' +import { useDetailedPresentation } from './presentation-fixture.client.ts' import { StatsPills } from '../src/client/chat/StatsPills.tsx' import { zh } from '../src/client/locale.ts' import { chatSnapshotFixture } from './chat-snapshot-fixture.client.ts' @@ -1044,6 +1045,7 @@ describe('small branch tails', () => { it('AssistantMarkdown single-line reasoning summary skips the newline cut', () => { const view = render( ()} /> case 'assistant-step': - return ()} /> + return ()} usePresentation={props.usePresentation} /> case 'command': return ( { openView('trajectory', callId) }, @@ -1636,7 +1637,7 @@ describe('ChatView', () => { expect(turnProcessControl(view.container)?.getAttribute('aria-expanded')).toBe('false') expect(processRow.getAttribute('hidden')).toBe('until-found') - act(() => { h.setTranscriptView('normal') }) + act(() => { h.setTranscriptView('detailed') }) expect(turnProcessControl(view.container)).toBeNull() expect(processRow.getAttribute('hidden')).toBeNull() diff --git a/packages/client/ui-chat/tests/coverage-tails.client.spec.tsx b/packages/client/ui-chat/tests/coverage-tails.client.spec.tsx index 2a2883ebb3..bc759ada20 100644 --- a/packages/client/ui-chat/tests/coverage-tails.client.spec.tsx +++ b/packages/client/ui-chat/tests/coverage-tails.client.spec.tsx @@ -5,6 +5,7 @@ import { cleanup, render } from '@testing-library/react' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' import { AssistantMarkdown, type AssistantMarkdownProps } from '../src/client/chat/AssistantMarkdown.tsx' +import { useDetailedPresentation } from './presentation-fixture.client.ts' import { zh } from '../src/client/locale.ts' const t: AssistantMarkdownProps['t'] = makeTranslate(zh, commonZh) @@ -16,6 +17,7 @@ describe('tails', () => { it('AssistantMarkdown renders reasoning as a Think row and unknown blocks as JSON fallback', () => { const view = render( { expect(view.getByText(/未知内容块/)).toBeTruthy() const stopped = render( { // groups is layout noise (no text, no pulse, no interrupted marker). const empty = render( { ) expect(empty.container.firstChild).toBeNull() const blank = render( - , + , ) expect(blank.container.firstChild).toBeNull() }) diff --git a/packages/client/ui-chat/tests/gate-branch-tails.client.spec.tsx b/packages/client/ui-chat/tests/gate-branch-tails.client.spec.tsx index 8bfb4014b6..d97056af81 100644 --- a/packages/client/ui-chat/tests/gate-branch-tails.client.spec.tsx +++ b/packages/client/ui-chat/tests/gate-branch-tails.client.spec.tsx @@ -5,6 +5,7 @@ import { cleanup, render } from '@testing-library/react' import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' import { AssistantMarkdown, type AssistantMarkdownProps } from '../src/client/chat/AssistantMarkdown.tsx' +import { useDetailedPresentation } from './presentation-fixture.client.ts' import { StatsPills } from '../src/client/chat/StatsPills.tsx' import { zh } from '../src/client/locale.ts' import { chatSnapshotFixture } from './chat-snapshot-fixture.client.ts' @@ -22,6 +23,7 @@ describe('render branch tails', () => { it('AssistantMarkdown reasoning row is ok-state when not the streaming tail', () => { const view = render( { it('AssistantMarkdown reasoning as the streaming tail renders the running ring', () => { const view = render( { const calls: MessageImagesRenderOwner[] = [] const view = render( { const calls: MessageImagesRenderOwner[] = [] const view = render( { const calls: MessageImagesRenderOwner[] = [] const view = render( selector(presentationPolicyFor('detailed')) diff --git a/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx b/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx index dedfa9198f..e1f399208e 100644 --- a/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx +++ b/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx @@ -5,6 +5,7 @@ import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' import { zh } from '../src/client/locale.ts' import { AssistantMarkdown, type AssistantMarkdownProps } from '../src/client/chat/AssistantMarkdown.tsx' +import { useDetailedPresentation } from './presentation-fixture.client.ts' afterEach(() => { cleanup() @@ -20,16 +21,22 @@ describe('ReasoningRow', () => { ])('starts collapsed and preserves manual expansion when $kind arrives', (nextBlock) => { const reasoning = { kind: 'reasoning' as const, text: 'Inspect the session\nCheck persistence' } const view = render( - , + , ) expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('false') fireEvent.click(view.getByText('思考')) view.rerender( - , + , ) expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true') view.rerender( - , + , ) expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true') expect(view.getByText(/Check persistence/)).toBeTruthy() @@ -40,6 +47,7 @@ describe('ReasoningRow', () => { it('follows the latest streaming line, then restores the settled first line', () => { const view = render( { view.rerender( { view.rerender( { it('expands from either Think or the reasoning summary', () => { const view = render( { ])('strips double-asterisk markers from the $label summary and renders body emphasis', ({ text, streaming }) => { const view = render( { .join('\n\n') + '\n\nReasoning body.' const view = render( { const first = '## Investigation\n\n**Check persistence**\n\n' const view = render( { const text = first + Array.from({ length: 8 }, (_, index) => `Paragraph ${index}.`).join('\n\n') view.rerender( { it('expanded Think drops the inline summary and renders prose without an IN card', () => { const view = render( { it('anchors the sticky-header selector: only an open Think row nests the disclosure row under data-expanded and data-open', () => { const view = render( { current = () => policy.mode.getSnapshot() expect(policy.mode.getSnapshot()).toBe('compact') - policy.setMode('normal') - expect(policy.mode.getSnapshot()).toBe('normal') - expect(observed).toEqual(['transcriptView=normal:normal']) - expect(host.set).toHaveBeenCalledWith('transcriptView', 'normal') + policy.setMode('detailed') + expect(policy.mode.getSnapshot()).toBe('detailed') + expect(observed).toEqual(['transcriptView=detailed:detailed']) + expect(host.set).toHaveBeenCalledWith('transcriptView', 'detailed') }) - it('adopts Host state and ignores identical writes', () => { + it('adopts Host state, reads the legacy value as Detailed, and ignores identical writes', () => { const host = stubSettingsScope() const policy = new TranscriptViewPolicy(host.scope) host.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'normal', performanceUsage: 'detailed' }, revision: 1, writable: true }) - expect(policy.mode.getSnapshot()).toBe('normal') - policy.setMode('normal') + expect(policy.mode.getSnapshot()).toBe('detailed') + policy.setMode('detailed') expect(host.set).not.toHaveBeenCalled() host.publish({ value: { linkOpening: 'sidebar', transcriptView: 'compact', performanceUsage: 'detailed' }, revision: 2 }) @@ -41,7 +41,7 @@ describe('TranscriptViewPolicy', () => { it('adopts an accepted section standing at construction', () => { const host = stubSettingsScope() - host.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'normal', performanceUsage: 'detailed' }, revision: 1, writable: true }) - expect(new TranscriptViewPolicy(host.scope).mode.getSnapshot()).toBe('normal') + host.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'expanded', performanceUsage: 'detailed' }, revision: 1, writable: true }) + expect(new TranscriptViewPolicy(host.scope).mode.getSnapshot()).toBe('expanded') }) }) diff --git a/packages/client/ui-chat/tests/transcript-view-row.client.spec.tsx b/packages/client/ui-chat/tests/transcript-view-row.client.spec.tsx index 82c928ac97..a5887a4e1e 100644 --- a/packages/client/ui-chat/tests/transcript-view-row.client.spec.tsx +++ b/packages/client/ui-chat/tests/transcript-view-row.client.spec.tsx @@ -9,7 +9,7 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { TranscriptViewRow, type TranscriptViewRowProps } from '../src/client/settings/TranscriptViewRow.tsx' import { PerformanceUsageRow } from '../src/client/settings/PerformanceUsageRow.tsx' -import type { LinkOpening, PerformanceUsageMode } from '../src/chat-settings.ts' +import type { LinkOpening, PerformanceUsageMode, TranscriptViewMode } from '../src/chat-settings.ts' import { LinkOpeningRow } from '../src/client/settings/LinkOpeningRow.tsx' import { en, zh } from '../src/client/locale.ts' @@ -34,9 +34,9 @@ function noPendingInteraction() { // The resource hook the resources plugin merges into GlobalStandardProps; this row reads no address. const useResource = (() => ({ status: 'none' as const, value: undefined, failure: undefined })) as GlobalStandardProps['useResource'] -function mount(mode: 'normal' | 'compact' = 'compact', dictionary: typeof en | typeof zh = en) { - const source = createSnapshotStore(mode) - const setTranscriptView = vi.fn((next: 'normal' | 'compact') => { source.set(next) }) +function mount(mode: TranscriptViewMode = 'compact', dictionary: typeof en | typeof zh = en) { + const source = createSnapshotStore(mode) + const setTranscriptView = vi.fn((next: TranscriptViewMode) => { source.set(next) }) const props: TranscriptViewRowProps = { usePanelInfo: selector => selector({ activePanelId: null }), useSessions: emptySessions(), diff --git a/packages/client/ui-conversation/src/client/locales.ts b/packages/client/ui-conversation/src/client/locales.ts index 464ff55e17..c164dc8535 100644 --- a/packages/client/ui-conversation/src/client/locales.ts +++ b/packages/client/ui-conversation/src/client/locales.ts @@ -286,7 +286,7 @@ export const zh = { 'row.inspect': '查看', 'tool.title.search': '搜索', 'tool.title.read': '读取', - 'tool.title.bash': 'Bash', + 'tool.title.bash': '运行命令', 'tool.title.write': '写入', 'tool.title.edit': '编辑', 'tool.title.code': '代码', @@ -295,10 +295,10 @@ export const zh = { 'tool.title.runCordis': '运行 Cordis 插件', 'tool.title.stopCordis': '停止 Cordis 插件', 'tool.title.removeCordis': '移除 Cordis 插件', - 'tool.title.pwsh': 'Pwsh', + 'tool.title.pwsh': '运行命令', 'tool.title.readImage': '读取图片', - 'tool.title.grep': 'Grep', - 'tool.title.glob': 'Glob', + 'tool.title.grep': '搜索文件内容', + 'tool.title.glob': '查找文件', 'tool.title.webSearch': '网页搜索', 'tool.title.webFetch': '网页获取', 'tool.autoReviewRejected': 'Auto review 已拒绝', diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index dde0b3eec5..5e3699e8e5 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-primitives/README.md -README.md: 12fe2648e383189198ff972709819e6f1eb4c02f -README.zh.md: 3c6f62fee22c5ad7e750c860724f60ca6dd9fbcf +README.md: 2606bd0dd5895319c9887b15497b2ca6b7a045ce +README.zh.md: cdf816549ea6cf12382b819a493ded7f61ecddd9 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index 12fe2648e3..2606bd0dd5 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -46,7 +46,7 @@ Check this table before writing a control in a feature package. A plugin cannot | `Tag` | Read-only capsule badge; `tone` selects one of eight palettes. | | `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 so every visible loader rotates in phase. `aria-hidden`, so the render site owns the name. | | `ConnectionIndicator` | Inline connection-recovery control across outage, retry, and recovered states. | -| `DisclosureRow` | 24px compact disclosure that lays title and content side by side. | +| `DisclosureRow` | 24px compact disclosure that lays title and content side by side. Memoized with shallow prop comparison; keep callbacks and React-node props stable when their content is unchanged. | | `Modal` | Centered dialog over a page mask. | | `RiskConfirmation` | Sensitive action gated behind an explicit checkbox. | | `OnboardingSurface` | First-run stage that holds the application root inert. | diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 3c6f62fee2..cdf816549e 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -46,7 +46,7 @@ kind: "package-library" | `Tag` | 只读胶囊徽章;`tone` 选择八种配色之一。 | | `StateDot` | 10px 槽内的绿色 `done`、琥珀色 `warning`、红色 `error`、中性灰色 `idle` 圆点,以及 tertiary 灰色 14px 旋转 `ongoing` loading,其动画固定到文档时间零点,所以所有可见 loading 同相旋转。它是 `aria-hidden` 的,名称由渲染点提供。 | | `ConnectionIndicator` | 行内连接恢复控件,覆盖断线、重试与已恢复三种状态。 | -| `DisclosureRow` | 24px 紧凑折叠行,标题与内容左右排列。 | +| `DisclosureRow` | 24px 紧凑折叠行,标题与内容左右排列。使用浅层 prop 比较进行 memo;内容未变时,保持回调与 React 节点 prop 的引用稳定。 | | `Modal` | 页面遮罩之上的居中对话框。 | | `RiskConfirmation` | 以显式复选框把关的敏感操作确认。 | | `OnboardingSurface` | 首次运行的引导舞台,期间保持应用根节点 inert。 | diff --git a/packages/client/ui-primitives/src/DisclosureRow.tsx b/packages/client/ui-primitives/src/DisclosureRow.tsx index f79b7e4720..5644772bc0 100644 --- a/packages/client/ui-primitives/src/DisclosureRow.tsx +++ b/packages/client/ui-primitives/src/DisclosureRow.tsx @@ -1,4 +1,4 @@ -import { type KeyboardEvent, type MouseEvent, type ReactNode } from 'react' +import { memo, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react' import clsx from 'clsx' import { IconChevronDownOutlineRegular } from './icons/index.tsx' import css from './DisclosureRow.module.css' @@ -27,10 +27,11 @@ export interface DisclosureRowProps { /** * Render one disclosure header and its controlled expanded content. + * Shallow prop comparison requires stable callbacks and React nodes to skip unchanged renders. * @param props - Visual content, controlled state, and interaction policy. * @returns the disclosure row. */ -export function DisclosureRow({ +export const DisclosureRow = memo(function DisclosureRow({ icon, title, open, @@ -101,4 +102,4 @@ export function DisclosureRow({ {open && children}
) -} +}) diff --git a/packages/client/ui-skill/src/client/locales.ts b/packages/client/ui-skill/src/client/locales.ts index d7a9b94228..ebd0910324 100644 --- a/packages/client/ui-skill/src/client/locales.ts +++ b/packages/client/ui-skill/src/client/locales.ts @@ -5,7 +5,7 @@ export const NS = 'skill' /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { - 'row.title': 'Skill', + 'row.title': '加载技能', 'row.running': '正在加载 skill', 'row.failed': 'skill 加载失败', 'row.stopped': 'skill 加载已中止', From e24805a53616e5624fa4652b8dae22e7750f7a6e Mon Sep 17 00:00:00 2001 From: imccyu Date: Sun, 20 Sep 2026 21:56:54 +0800 Subject: [PATCH 18/27] feat(ui-chat): refine reasoning previews and disclosure cues --- .../client/chat/GenericCommandCard.module.css | 7 +++++ .../src/client/chat/ReasoningRow.module.css | 11 ++----- .../ui-chat/src/client/chat/ReasoningRow.tsx | 29 ++++++++++++++----- .../ui-primitives/src/DisclosureRow.tsx | 4 +-- .../client/tool/components/ToolRow.module.css | 11 +++++++ .../tool/toolviews/bash-sample.module.css | 7 +++++ .../src/client/tool/toolviews/bash-sample.tsx | 6 ++-- 7 files changed, 55 insertions(+), 20 deletions(-) diff --git a/packages/client/ui-chat/src/client/chat/GenericCommandCard.module.css b/packages/client/ui-chat/src/client/chat/GenericCommandCard.module.css index 513a826c46..eddba8e53d 100644 --- a/packages/client/ui-chat/src/client/chat/GenericCommandCard.module.css +++ b/packages/client/ui-chat/src/client/chat/GenericCommandCard.module.css @@ -39,6 +39,7 @@ .title { font-weight: 400; + transition: color 100ms ease; } .separator { @@ -59,6 +60,12 @@ line-height: calc(24px + var(--dsh-content-font-delta, 0px)); text-overflow: ellipsis; white-space: nowrap; + transition: color 100ms ease; +} + +.row:hover .title, +.row:hover .summary:not([data-error]) { + color: var(--dsw-alias-label-primary); } .summary[data-error], diff --git a/packages/client/ui-chat/src/client/chat/ReasoningRow.module.css b/packages/client/ui-chat/src/client/chat/ReasoningRow.module.css index 5e98217171..f59c04e404 100644 --- a/packages/client/ui-chat/src/client/chat/ReasoningRow.module.css +++ b/packages/client/ui-chat/src/client/chat/ReasoningRow.module.css @@ -83,17 +83,12 @@ text-overflow: ellipsis; } -.summary[data-follow-end] { - display: flex; - justify-content: flex-end; +.summary[data-streaming] { + mask-image: linear-gradient(to right, black calc(100% - 48px), transparent); } -.summary[data-follow-end] .summaryText { - flex: 0 0 auto; - width: max-content; - min-width: 100%; +.summary[data-streaming] .summaryText { overflow: visible; - text-align: start; text-overflow: clip; } diff --git a/packages/client/ui-chat/src/client/chat/ReasoningRow.tsx b/packages/client/ui-chat/src/client/chat/ReasoningRow.tsx index 2d01eeb7fd..53d1ab2a55 100644 --- a/packages/client/ui-chat/src/client/chat/ReasoningRow.tsx +++ b/packages/client/ui-chat/src/client/chat/ReasoningRow.tsx @@ -13,17 +13,29 @@ function firstLine(text: string): string { return newline === -1 ? text : text.slice(0, newline) } -function latestLine(text: string): string { - const visible = text.trimEnd() - const newline = visible.lastIndexOf('\n') - return newline === -1 ? visible : visible.slice(newline + 1) +function latestCompletedParagraphFirstLine(text: string): string { + let summary = '' + let paragraphStart = 0 + const separator = /\r?\n[\t ]*\r?\n/g + while (true) { + const nextParagraph = separator.exec(text) + const paragraphEnd = nextParagraph === null ? text.length + : nextParagraph.index + nextParagraph[0].indexOf('\n') + const newline = text.indexOf('\n', paragraphStart) + if (newline !== -1 && newline <= paragraphEnd) { + const candidate = text.slice(paragraphStart, newline).trim() + if (candidate !== '') summary = candidate + } + if (nextParagraph === null) return summary + paragraphStart = nextParagraph.index + nextParagraph[0].length + } } /** * Render one assistant reasoning block collapsed until the reader opens it. The * collapsed summary omits double-asterisk markers; expanded content renders - * the complete Markdown with secondary typography. A streaming row always - * previews its latest line. Mode changes toggle CSS display without unmounting + * the complete Markdown with secondary typography. A streaming preview advances + * when a paragraph's first line completes. Mode changes toggle CSS display without unmounting * collapsed summaries. * @param props.text - complete or streaming reasoning text. * @param props.running - whether this block is the streaming tail. @@ -40,13 +52,14 @@ export const ReasoningRow = memo(function ReasoningRow({ text, running, usePrese const [expanded, setExpanded] = useState(false) const labels = useMemo(() => markdownLabels(t), [t]) const toggle = useCallback(() => { setExpanded(value => !value) }, []) - const summary = (running ? latestLine(text) : firstLine(text)).replaceAll('**', '') + const summaryText = running ? latestCompletedParagraphFirstLine(text) : firstLine(text) + const summary = useMemo(() => summaryText.replaceAll('**', ''), [summaryText]) const preview = usePresentation(policy => !expanded && summary !== '' && (running || policy.settledReasoningPreview)) const collapsedContent = useMemo(() => ( <> - + {summary} diff --git a/packages/client/ui-primitives/src/DisclosureRow.tsx b/packages/client/ui-primitives/src/DisclosureRow.tsx index 5644772bc0..c2a59ce0c0 100644 --- a/packages/client/ui-primitives/src/DisclosureRow.tsx +++ b/packages/client/ui-primitives/src/DisclosureRow.tsx @@ -1,6 +1,6 @@ import { memo, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react' import clsx from 'clsx' -import { IconChevronDownOutlineRegular } from './icons/index.tsx' +import { IconChevronDownOutlineRegular, IconChevronUpOutlineRegular } from './icons/index.tsx' import css from './DisclosureRow.module.css' /** Shared 24px disclosure chrome for compact flow rows. */ @@ -67,7 +67,7 @@ export const DisclosureRow = memo(function DisclosureRow({ ) : icon const leading = open - ? + ? : collapsedLeading return ( diff --git a/packages/client/ui-tool/src/client/tool/components/ToolRow.module.css b/packages/client/ui-tool/src/client/tool/components/ToolRow.module.css index 520e800a3a..73efca2964 100644 --- a/packages/client/ui-tool/src/client/tool/components/ToolRow.module.css +++ b/packages/client/ui-tool/src/client/tool/components/ToolRow.module.css @@ -67,6 +67,7 @@ .title { font-weight: 400; + transition: color 100ms ease; } .sep { @@ -87,6 +88,7 @@ font-size: var(--dsh-content-font-size-secondary, 13px); line-height: calc(24px + var(--dsh-content-font-delta, 0px)); color: var(--dsw-alias-label-tertiary); + transition: color 100ms ease; } /* Trailing summary fragment kept out of .summary's ellipsis, for a count whose @@ -101,6 +103,13 @@ font-size: var(--dsh-content-font-size-secondary, 13px); line-height: calc(24px + var(--dsh-content-font-delta, 0px)); color: var(--dsw-alias-label-tertiary); + transition: color 100ms ease; +} + +.row:hover .title, +.row:hover .summary:not(.errorSummary), +.row:hover .summarySuffix { + color: var(--dsw-alias-label-primary); } /* Diff-row +/- totals: the code font, matching the diff body the numbers @@ -143,8 +152,10 @@ text-decoration-thickness: 1px; text-underline-offset: 3px; cursor: pointer; + transition: color 100ms ease; } +.row:hover .fileLink, .fileLink:hover { color: var(--dsw-alias-label-primary); text-decoration-color: currentColor; diff --git a/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.module.css b/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.module.css index ab8acd692c..e45e761ab3 100644 --- a/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.module.css +++ b/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.module.css @@ -172,6 +172,7 @@ font-size: var(--dsh-content-font-size-secondary, 13px); line-height: calc(24px + var(--dsh-content-font-delta, 0px)); color: var(--dsw-alias-label-secondary); + transition: color 100ms ease; } .sep { @@ -192,6 +193,12 @@ font-size: var(--dsh-content-font-size-secondary, 13px); line-height: calc(24px + var(--dsh-content-font-delta, 0px)); color: var(--dsw-alias-label-tertiary); + transition: color 100ms ease; +} + +.root:hover .title, +.root:hover .summary:not(.errorSummary) { + color: var(--dsw-alias-label-primary); } /* Error row's collapsed summary: the failure's first line in the error color. */ diff --git a/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.tsx b/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.tsx index 7b1f8653c5..7c52b380e1 100644 --- a/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.tsx +++ b/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.tsx @@ -2,7 +2,8 @@ import { useMemo, useState, type KeyboardEvent } from 'react' import type { Context } from '@deepseek-ai/cordis' import clsx from 'clsx' import { - IconApiOutlineRegular, IconChevronDownOutlineRegular, IconInspectOutlineRegular, TerminalBlock, + IconApiOutlineRegular, IconChevronDownOutlineRegular, IconChevronUpOutlineRegular, IconInspectOutlineRegular, + TerminalBlock, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { ToolCallViewProps } from '../../contract/slots.ts' @@ -25,6 +26,7 @@ function stateStatus(state: ToolRowState, t: BashRowProps['t']): string | null { switch (state) { case 'running': return t('bash.running') case 'error': return t('bash.failed') + case 'stopped': return t('bash.stopped') default: return null } } @@ -71,7 +73,7 @@ export function BashRow({ toolName, block, sessionId, useSessions, inspect, t }: } const businessIcon = const leading = open - ? + ? : expandable ? ( <> From 007241d2a8e242c09ecf9a8a0434f071f9323a82 Mon Sep 17 00:00:00 2001 From: imccyu Date: Sun, 20 Sep 2026 22:08:38 +0800 Subject: [PATCH 19/27] feat(ui-chat): add text shimmer to running rows --- .../client/chat/GenericCommandCard.module.css | 32 ----------------- .../src/client/chat/GenericCommandCard.tsx | 8 +++-- .../ui-primitives/src/DisclosureRow.tsx | 6 +++- .../ui-primitives/src/TextShimmer.module.css | 27 ++++++++++++++ .../client/ui-primitives/src/TextShimmer.tsx | 23 ++++++++++++ packages/client/ui-primitives/src/index.ts | 2 ++ .../client/tool/components/ToolRow.module.css | 36 ++----------------- .../src/client/tool/components/ToolRow.tsx | 10 +++--- .../tool/toolviews/bash-sample.module.css | 25 ------------- .../src/client/tool/toolviews/bash-sample.tsx | 7 ++-- 10 files changed, 76 insertions(+), 100 deletions(-) create mode 100644 packages/client/ui-primitives/src/TextShimmer.module.css create mode 100644 packages/client/ui-primitives/src/TextShimmer.tsx diff --git a/packages/client/ui-chat/src/client/chat/GenericCommandCard.module.css b/packages/client/ui-chat/src/client/chat/GenericCommandCard.module.css index eddba8e53d..a4bb6ef0cc 100644 --- a/packages/client/ui-chat/src/client/chat/GenericCommandCard.module.css +++ b/packages/client/ui-chat/src/client/chat/GenericCommandCard.module.css @@ -3,32 +3,6 @@ flex-direction: column; } -.row { - position: relative; - overflow: hidden; -} - -.root[data-state='running'] .row::after { - content: ''; - position: absolute; - inset-block: 0; - left: 0; - width: 300px; - background: linear-gradient( - 90deg, - transparent 0%, - color-mix(in srgb, var(--dsw-alias-bg-base) 60%, transparent) 55%, - transparent 100% - ); - animation: dsh-command-row-sweep 2.6s ease-out infinite; - pointer-events: none; -} - -@keyframes dsh-command-row-sweep { - 0% { left: -300px; } - 90%, 100% { left: 100%; } -} - .leading { flex-shrink: 0; } @@ -85,9 +59,3 @@ font: var(--dsw-font-markdown-code-block-small); white-space: pre-wrap; } - -@media (prefers-reduced-motion: reduce) { - .root[data-state='running'] .row::after { - animation: none; - } -} diff --git a/packages/client/ui-chat/src/client/chat/GenericCommandCard.tsx b/packages/client/ui-chat/src/client/chat/GenericCommandCard.tsx index 2864836301..0374637e17 100644 --- a/packages/client/ui-chat/src/client/chat/GenericCommandCard.tsx +++ b/packages/client/ui-chat/src/client/chat/GenericCommandCard.tsx @@ -1,6 +1,6 @@ import { useState } from 'react' import type { ChatViewSlotProps, CommandRowOwnerProps } from '../contract/slots.ts' -import { DisclosureRow, IconApiOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' +import { DisclosureRow, IconApiOutlineRegular, TextShimmer } from '@deepseek-ai/dsh-client-ui-primitives' import a11yCss from './accessibility.module.css' import css from './GenericCommandCard.module.css' @@ -29,6 +29,7 @@ export function GenericCommandCard({ node, t, runningSummary }: GenericCommandCa // command name. const title = node.name ?? t('command.title') const state = stateOf(node.outcome) + const running = state === 'running' const body = text !== undefined && text.includes('\n') ? text : null const open = expanded && body !== null return ( @@ -42,6 +43,7 @@ export function GenericCommandCard({ node, t, runningSummary }: GenericCommandCa chevronClassName={css.chevron} icon={} title={title} + running={running} open={open} expandable={body !== null} expandOnRowClick @@ -50,7 +52,9 @@ export function GenericCommandCard({ node, t, runningSummary }: GenericCommandCa collapsedContent={( <> - {summary} + + {summary} + )} > diff --git a/packages/client/ui-primitives/src/DisclosureRow.tsx b/packages/client/ui-primitives/src/DisclosureRow.tsx index c2a59ce0c0..a4fa7a2124 100644 --- a/packages/client/ui-primitives/src/DisclosureRow.tsx +++ b/packages/client/ui-primitives/src/DisclosureRow.tsx @@ -1,6 +1,7 @@ import { memo, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react' import clsx from 'clsx' import { IconChevronDownOutlineRegular, IconChevronUpOutlineRegular } from './icons/index.tsx' +import { TextShimmer } from './TextShimmer.tsx' import css from './DisclosureRow.module.css' /** Shared 24px disclosure chrome for compact flow rows. */ @@ -10,6 +11,8 @@ export interface DisclosureRowProps { open: boolean expandable: boolean onToggle: () => void + /** Animate the title while its owning operation is running. */ + running?: boolean | undefined /** Makes the complete title row the disclosure target. */ expandOnRowClick?: boolean | undefined /** Replaces the collapsed icon with a chevron while the row is hovered. */ @@ -37,6 +40,7 @@ export const DisclosureRow = memo(function DisclosureRow({ open, expandable, onToggle, + running = false, expandOnRowClick = false, previewChevron = expandable, keepContentWhenOpen = false, @@ -96,7 +100,7 @@ export const DisclosureRow = memo(function DisclosureRow({ {leading} )} - {title} + {title} {(keepContentWhenOpen || !open) && collapsedContent} {open && children} diff --git a/packages/client/ui-primitives/src/TextShimmer.module.css b/packages/client/ui-primitives/src/TextShimmer.module.css new file mode 100644 index 0000000000..bdc2de9a44 --- /dev/null +++ b/packages/client/ui-primitives/src/TextShimmer.module.css @@ -0,0 +1,27 @@ +.root[data-text-shimmer] { + background-image: linear-gradient( + 90deg, + currentColor calc(50% - var(--dsh-text-shimmer-spread)), + color-mix(in oklab, currentColor 50%, transparent), + currentColor calc(50% + var(--dsh-text-shimmer-spread)) + ); + background-position: 100% center; + background-repeat: no-repeat; + background-size: 250% 100%; + background-clip: text; + -webkit-background-clip: text; + -webkit-text-fill-color: transparent; + animation: dsh-text-shimmer 1.5s cubic-bezier(0.33, 0, 0.67, 1) infinite; +} + +@keyframes dsh-text-shimmer { + 66.6667%, 100% { background-position: 0% center; } +} + +@media (prefers-reduced-motion: reduce) { + .root[data-text-shimmer] { + background-image: none; + -webkit-text-fill-color: currentColor; + animation: none; + } +} diff --git a/packages/client/ui-primitives/src/TextShimmer.tsx b/packages/client/ui-primitives/src/TextShimmer.tsx new file mode 100644 index 0000000000..8249626435 --- /dev/null +++ b/packages/client/ui-primitives/src/TextShimmer.tsx @@ -0,0 +1,23 @@ +/** Text-only activity animation with a stable span across lifecycle changes. */ +import { memo, useMemo, type CSSProperties } from 'react' +import clsx from 'clsx' +import css from './TextShimmer.module.css' + +/** Text and activity supplied by the owning row. */ +export interface TextShimmerProps { + children: string + active: boolean + className?: string | undefined +} + +/** + * Render text with an optional moving highlight; inactive text keeps the same node. + * @param props - localized text, running state, and owner styling. + * @returns the retained text span. + */ +export const TextShimmer = memo(function TextShimmer({ children, active, className }: TextShimmerProps) { + const style = useMemo(() => ({ + '--dsh-text-shimmer-spread': `${children.length * 8}px`, + } as CSSProperties), [children.length]) + return {children} +}) diff --git a/packages/client/ui-primitives/src/index.ts b/packages/client/ui-primitives/src/index.ts index 25ba54ea24..551ced88ea 100644 --- a/packages/client/ui-primitives/src/index.ts +++ b/packages/client/ui-primitives/src/index.ts @@ -6,6 +6,8 @@ export { StateDot } from './StateDot.tsx' export type { StateDotState } from './StateDot.tsx' export { DisclosureRow } from './DisclosureRow.tsx' export type { DisclosureRowProps } from './DisclosureRow.tsx' +export { TextShimmer } from './TextShimmer.tsx' +export type { TextShimmerProps } from './TextShimmer.tsx' export { Button } from './Button.tsx' export type { ButtonVariant } from './Button.tsx' export { Pill } from './Pill.tsx' diff --git a/packages/client/ui-tool/src/client/tool/components/ToolRow.module.css b/packages/client/ui-tool/src/client/tool/components/ToolRow.module.css index 73efca2964..3bf04ae4ac 100644 --- a/packages/client/ui-tool/src/client/tool/components/ToolRow.module.css +++ b/packages/client/ui-tool/src/client/tool/components/ToolRow.module.css @@ -11,37 +11,6 @@ flex-direction: column; } -.row { - position: relative; /* sweep-glare overlay anchor */ - overflow: hidden; -} - -/* Running sweep (deepsuite ShimmerText pattern): a fixed-width glare band — - theme background at 60% — glides over the row content from off-left to - off-right, washing glyphs and icon toward the background as it passes. - ease-out with a 10% end hold gives each pass a beat before the next. */ -.root[data-state='running'] .row::after { - content: ''; - position: absolute; - top: 0; - bottom: 0; - left: 0; - width: 300px; - background: linear-gradient( - 90deg, - transparent 0%, - color-mix(in srgb, var(--dsw-alias-bg-base) 60%, transparent) 55%, - transparent 100% - ); - animation: dsh-tool-row-sweep 2.6s ease-out infinite; - pointer-events: none; -} - -@keyframes dsh-tool-row-sweep { - 0% { left: -300px; } - 90%, 100% { left: 100%; } -} - .leading { flex-shrink: 0; } @@ -371,8 +340,9 @@ border: 0.5px solid var(--dsw-alias-border-l1); } -/* Visually hidden run-state label for assistive technology: the running sweep - and settlement summary tones are color-only. */ +/* Visually hidden run-state label for assistive technology: the business icon + and animated text treatment do not name the state, so this text carries the + running/failed/interrupted state to a screen reader. */ .visuallyHidden { position: absolute; width: 1px; diff --git a/packages/client/ui-tool/src/client/tool/components/ToolRow.tsx b/packages/client/ui-tool/src/client/tool/components/ToolRow.tsx index 3799370527..874beb9252 100644 --- a/packages/client/ui-tool/src/client/tool/components/ToolRow.tsx +++ b/packages/client/ui-tool/src/client/tool/components/ToolRow.tsx @@ -2,7 +2,7 @@ import { useMemo, useState, type KeyboardEvent, type MouseEvent, type ReactNode import clsx from 'clsx' import { CodeBlock, DiffBlock, DisclosureRow, IconInspectOutlineRegular, ReadBlock, SearchBlock, - TerminalBlock, WebBlock, + TerminalBlock, TextShimmer, WebBlock, diffTotals, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsRenderSlots, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' @@ -156,6 +156,7 @@ export function ToolRow({ [card, inputRaw, open, variant], ) const status = stateStatus(state, t) + const running = state === 'running' const normalSummary = terminalBody?.description ?? (open ? detailsBody?.expandedSummary ?? summary : summary) // A failure keeps its first result line when available and otherwise turns // the ordinary summary red. An interruption turns the tool-owned summary @@ -202,6 +203,7 @@ export function ToolRow({ chevronClassName={css.chevron} icon={icon} title={title} + running={running} open={open} expandable={expandable} expandOnRowClick @@ -219,7 +221,7 @@ export function ToolRow({ onClick={openFile} onKeyDown={fileLinkKeyDown} > - {summaryText} + {summaryText} ) : ( - {summaryText} + {summaryText} )} {suffix !== null && ( - {suffix} + {suffix} )} )} diff --git a/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.module.css b/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.module.css index e45e761ab3..be9b547ce6 100644 --- a/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.module.css +++ b/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.module.css @@ -85,37 +85,12 @@ } .root { - position: relative; /* sweep-glare overlay anchor */ - overflow: hidden; display: flex; align-items: center; height: calc(24px + var(--dsh-content-font-delta, 0px)); min-width: 0; } -/* Running sweep glare — same deepsuite ShimmerText pattern as ToolRow. */ -.root[data-state='running']::after { - content: ''; - position: absolute; - top: 0; - bottom: 0; - left: 0; - width: 300px; - background: linear-gradient( - 90deg, - transparent 0%, - color-mix(in srgb, var(--dsw-alias-bg-base) 60%, transparent) 55%, - transparent 100% - ); - animation: dsh-bash-row-sweep 2.6s ease-out infinite; - pointer-events: none; -} - -@keyframes dsh-bash-row-sweep { - 0% { left: -300px; } - 90%, 100% { left: 100%; } -} - .leading { position: relative; /* .chevronHover overlay anchor */ flex: none; diff --git a/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.tsx b/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.tsx index 7c52b380e1..37b1d355d0 100644 --- a/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.tsx +++ b/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.tsx @@ -3,7 +3,7 @@ import type { Context } from '@deepseek-ai/cordis' import clsx from 'clsx' import { IconApiOutlineRegular, IconChevronDownOutlineRegular, IconChevronUpOutlineRegular, IconInspectOutlineRegular, - TerminalBlock, + TerminalBlock, TextShimmer, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { ToolCallViewProps } from '../../contract/slots.ts' @@ -63,6 +63,7 @@ export function BashRow({ toolName, block, sessionId, useSessions, inspect, t }: const settlementLine = state === 'error' ? model.errorSummary ?? normalSummary : state === 'stopped' ? t('bash.stopped') : null + const running = state === 'running' const toggleExpand = () => { setExpanded(v => !v) } @@ -98,14 +99,14 @@ export function BashRow({ toolName, block, sessionId, useSessions, inspect, t }: > {leading} {status !== null && {status}} - {t(model.titleKey)} + {t(model.titleKey)} - {settlementLine ?? normalSummary} + {settlementLine ?? normalSummary} {open && ( From b6f99fad556a1bfe7d8fe106e91b58a162ba532c Mon Sep 17 00:00:00 2001 From: imccyu Date: Sun, 20 Sep 2026 22:19:45 +0800 Subject: [PATCH 20/27] feat(ui-chat): filter system prompts and permission commands --- .../ui-chat/src/client/contract/chat-visibility.ts | 13 +++++++++++++ .../conversation-nodes/chat-snapshot-builder.ts | 3 ++- .../client/conversation-nodes/turn-navigation.ts | 3 ++- .../conversation-nodes/turn-process-presentation.ts | 3 ++- 4 files changed, 19 insertions(+), 3 deletions(-) create mode 100644 packages/client/ui-chat/src/client/contract/chat-visibility.ts diff --git a/packages/client/ui-chat/src/client/contract/chat-visibility.ts b/packages/client/ui-chat/src/client/contract/chat-visibility.ts new file mode 100644 index 0000000000..7e66c15ca5 --- /dev/null +++ b/packages/client/ui-chat/src/client/contract/chat-visibility.ts @@ -0,0 +1,13 @@ +/** Chat-only row visibility; durable events and trajectory inspection remain intact. */ +import type { ChatNode } from './chat-nodes.ts' + +/** + * Exclude system prompts and permission commands from visible Chat rows. + * @param node - projected Chat node. + * @returns whether the node contributes a visible Chat row. + */ +export function isVisibleChatNode(node: ChatNode): boolean { + return node.visibility === 'visible' + && node.kind !== 'system-prompt' + && !(node.kind === 'command' && node.data.name === 'permission') +} diff --git a/packages/client/ui-chat/src/client/conversation-nodes/chat-snapshot-builder.ts b/packages/client/ui-chat/src/client/conversation-nodes/chat-snapshot-builder.ts index fb91233786..8c805e6107 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/chat-snapshot-builder.ts +++ b/packages/client/ui-chat/src/client/conversation-nodes/chat-snapshot-builder.ts @@ -6,6 +6,7 @@ import type { } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { ChatConversationViewNode, ChatNode } from '../contract/chat-nodes.ts' import { isRunningTool } from '../contract/chat-nodes.ts' +import { isVisibleChatNode } from '../contract/chat-visibility.ts' import type { ChatLocationNodeIndex, ChatNodeProcessSource, ChatNodeSource, ChatNodeStore, ChatSnapshot, ChatTurnNavigationIndex, ChatTurnProcessPresentation, LegacyConversationSlice, TurnNavigationItem, @@ -400,7 +401,7 @@ function presentationPosition( export function orderedVisibleChatNodes( nodes: readonly ChatConversationViewNode[], ): ChatConversationViewNode[] { - const visible = nodes.filter(node => node.visibility === 'visible') + const visible = nodes.filter(node => isVisibleChatNode(node as ChatNode)) const presentations = turnProcessPresentations(visible) return visible.sort((left, right) => { const leftPosition = presentationPosition(left, presentations) diff --git a/packages/client/ui-chat/src/client/conversation-nodes/turn-navigation.ts b/packages/client/ui-chat/src/client/conversation-nodes/turn-navigation.ts index 331840e80c..d0f6c40798 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/turn-navigation.ts +++ b/packages/client/ui-chat/src/client/conversation-nodes/turn-navigation.ts @@ -1,3 +1,4 @@ +import { isVisibleChatNode } from '../contract/chat-visibility.ts' import type { ChatNode } from '../contract/chat-nodes.ts' import type { ChatLocationNodeIndex, ChatNodeStore, TurnNavigationItem } from '../contract/snapshot.ts' @@ -82,7 +83,7 @@ export function turnNavigationItem( ): TurnNavigationItem | undefined { const loaded = locations.getTurn(turn) .map(key => nodes.get(key)) - .filter((node): node is ChatNode => node !== undefined && node.visibility === 'visible') + .filter((node): node is ChatNode => node !== undefined && isVisibleChatNode(node as ChatNode)) const user = loaded.find(node => node.kind === 'user') const anchor = user ?? loaded[0] if (anchor === undefined) return undefined diff --git a/packages/client/ui-chat/src/client/conversation-nodes/turn-process-presentation.ts b/packages/client/ui-chat/src/client/conversation-nodes/turn-process-presentation.ts index 98a33a6c8b..d337954772 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/turn-process-presentation.ts +++ b/packages/client/ui-chat/src/client/conversation-nodes/turn-process-presentation.ts @@ -1,3 +1,4 @@ +import { isVisibleChatNode } from '../contract/chat-visibility.ts' import type { ChatNode } from '../contract/chat-nodes.ts' import type { ChatLocationNodeIndex, ChatNodeStore, ChatTurnProcessPresentation, @@ -49,7 +50,7 @@ function derivePresentation( let compactAnswer = true for (const key of keys) { const node = nodes.get(key) as ChatNode | undefined - if (node === undefined || node.kind === 'turn-process') continue + if (node === undefined || !isVisibleChatNode(node) || node.kind === 'turn-process') continue if ((node.kind === 'user' || node.kind === 'steering') && (openingHumanAnchor === undefined || node.anchorSeq > openingHumanAnchor) && (spec.answerAnchorSeq === null || node.anchorSeq < spec.answerAnchorSeq)) { From bcd14d776c4467d3e46875b397dc2499107858d5 Mon Sep 17 00:00:00 2001 From: imccyu Date: Sun, 20 Sep 2026 22:22:17 +0800 Subject: [PATCH 21/27] perf(ui-chat): memoize tool and command rows --- .../src/client/chat/GenericCommandCard.tsx | 40 ++- .../src/client/tool/components/ToolRow.tsx | 289 +++++++++--------- .../src/client/tool/toolviews/bash-sample.tsx | 36 ++- 3 files changed, 198 insertions(+), 167 deletions(-) diff --git a/packages/client/ui-chat/src/client/chat/GenericCommandCard.tsx b/packages/client/ui-chat/src/client/chat/GenericCommandCard.tsx index 0374637e17..0b0749881b 100644 --- a/packages/client/ui-chat/src/client/chat/GenericCommandCard.tsx +++ b/packages/client/ui-chat/src/client/chat/GenericCommandCard.tsx @@ -1,4 +1,4 @@ -import { useState } from 'react' +import { memo, useCallback, useMemo, useState } from 'react' import type { ChatViewSlotProps, CommandRowOwnerProps } from '../contract/slots.ts' import { DisclosureRow, IconApiOutlineRegular, TextShimmer } from '@deepseek-ai/dsh-client-ui-primitives' import a11yCss from './accessibility.module.css' @@ -6,6 +6,8 @@ import css from './GenericCommandCard.module.css' type CommandRowState = 'running' | 'ok' | 'error' +const COMMAND_ICON = + /** Node state → row state semantic (running while unsettled; outcome kind after). */ function stateOf(outcome: CommandRowOwnerProps['node']['outcome']): CommandRowState { if (outcome === null) return 'running' @@ -19,7 +21,12 @@ export interface GenericCommandCardProps extends CommandRowOwnerProps { runningSummary?: string | undefined } -export function GenericCommandCard({ node, t, runningSummary }: GenericCommandCardProps) { +/** + * Render a command summary and its lazily mounted multiline output. + * @param props - command, locale, and optional running label. + * @returns the command disclosure. + */ +export const GenericCommandCard = memo(function GenericCommandCard({ node, t, runningSummary }: GenericCommandCardProps) { const [expanded, setExpanded] = useState(false) const text = node.outcome?.text const summary = node.outcome === null @@ -32,6 +39,18 @@ export function GenericCommandCard({ node, t, runningSummary }: GenericCommandCa const running = state === 'running' const body = text !== undefined && text.includes('\n') ? text : null const open = expanded && body !== null + const toggle = useCallback(() => { setExpanded(value => !value) }, []) + const collapsedContent = useMemo(() => ( + <> + + + {summary} + + + ), [running, state, summary]) + const content = useMemo(() => open + ?
{body}
+ : undefined, [body, open, state]) return (
{state === 'running' && {t('row.running')}} @@ -41,25 +60,18 @@ export function GenericCommandCard({ node, t, runningSummary }: GenericCommandCa leadingClassName={css.leading} titleClassName={css.title} chevronClassName={css.chevron} - icon={} + icon={COMMAND_ICON} title={title} running={running} open={open} expandable={body !== null} expandOnRowClick keepContentWhenOpen - onToggle={() => { setExpanded(value => !value) }} - collapsedContent={( - <> - - - {summary} - - - )} + onToggle={toggle} + collapsedContent={collapsedContent} > -
{body}
+ {content}
) -} +}) diff --git a/packages/client/ui-tool/src/client/tool/components/ToolRow.tsx b/packages/client/ui-tool/src/client/tool/components/ToolRow.tsx index 874beb9252..62b91189fc 100644 --- a/packages/client/ui-tool/src/client/tool/components/ToolRow.tsx +++ b/packages/client/ui-tool/src/client/tool/components/ToolRow.tsx @@ -1,4 +1,4 @@ -import { useMemo, useState, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react' +import { memo, useCallback, useMemo, useState, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react' import clsx from 'clsx' import { CodeBlock, DiffBlock, DisclosureRow, IconInspectOutlineRegular, ReadBlock, SearchBlock, @@ -101,7 +101,12 @@ function stateStatus(state: ToolRowState, t: TranslateNS<'conversation'>): strin } } -export function ToolRow({ +/** + * Render one localized tool summary and lazily mounted result card. + * @param props - tool state, summary, output, and navigation callbacks. + * @returns the tool disclosure. + */ +export const ToolRow = memo(function ToolRow({ t, variant, toolName, @@ -134,9 +139,9 @@ export function ToolRow({ const readLabels = useMemo(() => readBlockLabels(t), [t]) const searchLabels = useMemo(() => searchBlockLabels(t), [t]) const webLabels = useMemo(() => webBlockLabels(t), [t]) - const terminalBody = terminal === undefined || terminal === null + const terminalBody = useMemo(() => terminal === undefined || terminal === null ? null - : localizeTerminalCardModel(terminal, t) + : localizeTerminalCardModel(terminal, t), [terminal, t]) const diffBody = diff ?? null const readBody = read ?? null const imageBody = image !== undefined && image !== null && renderSlot !== undefined && loadImage !== undefined @@ -173,26 +178,159 @@ export function ToolRow({ }, [diffBody]) const settledWithCue = state === 'error' || state === 'stopped' const suffix = settledWithCue ? null : summarySuffix ?? diffStat - const toggleExpand = () => { + const toggleExpand = useCallback(() => { setExpanded(v => !v) - } - const openFile = filePath !== undefined && onOpenFile !== undefined && !settledWithCue + }, []) + const openFile = useMemo(() => filePath !== undefined && onOpenFile !== undefined && !settledWithCue ? (event: MouseEvent) => { event.stopPropagation() if (filePathLine === undefined) onOpenFile(filePath) else onOpenFile(filePath, { line: filePathLine }) } - : undefined + : undefined, [filePath, filePathLine, onOpenFile, settledWithCue]) // Keep Enter/Space on the focused path link from bubbling to the row's // keydown handler, which would preventDefault() the key and toggle expand // instead of activating the link — the keyboard analogue of openFile's // stopPropagation. The native button still fires its own onClick from the key. - const fileLinkKeyDown = (event: KeyboardEvent) => { + const fileLinkKeyDown = useCallback((event: KeyboardEvent) => { if (event.key === 'Enter' || event.key === ' ') event.stopPropagation() - } + }, []) // The code variant's program renders through CodeBlock (shiki), so only its // output joins the IN/OUT card; every other variant's input does too. const cardBody = variant === 'code' ? null : bodyText + const collapsedContent = useMemo(() => summaryText !== '' && ( + /* An empty summary drops the separator with it (a row that is only + its title shows no trailing dot). */ + <> + + {openFile !== undefined ? ( + + ) : ( + + {summaryText} + + )} + {suffix !== null && ( + {suffix} + )} + + ), [diffStat, fileLinkKeyDown, openFile, running, state, suffix, summaryText]) + const expandedContent = useMemo(() => open ? ( +
+ {askQuestionBody !== null + ? + : terminalBody !== null + ? ( + + ) + : diffBody !== null + ? + : readBody !== null + ? + : imageBody !== null + ? ( + /* Label, gallery, then the result's OWN envelope text. The text + comes from the image card model (which reads the result's text + block), never from the row's flattened output: an image read's + content is [text envelope, image block] and flattening + JSON.stringifies the image block, printing the raw attachment + object under the picture. It is not redundant either — the + attachment slot can render nothing, and then this line is the + only evidence an image was returned. */ +
+
{imageBody.label}
+ {renderSlot !== undefined && loadImage !== undefined && renderSlot('tool.call.images', { + images: imageBody.images, + loadImage, + align: 'start', + })} +
{imageBody.text}
+
+ ) + : searchBody !== null + ? ( + <> + + {/* A capped search's recovery locator lives only in the result + text; show it below the card so the dropped rows survive. */} + {searchBody.recovery !== undefined && ( +
{searchBody.recovery}
+ )} + + ) + : webBody !== null + ? + : detailsBody !== null + ? + : ( + <> + {variant === 'code' && bodyText !== null && ( +
+ +
+ )} + {(cardBody !== null || outputText !== null) && ( +
+ {cardBody !== null && ( +
+ {t('row.input')} + {cardBody} +
+ )} + {cardBody !== null && outputText !== null && ( + + )} + {outputText !== null && ( +
+ {t('row.output')} + + {outputText} + +
+ )} +
+ )} + + )} + {inspect !== undefined && ( + + )} +
+ ) : undefined, [ + open, detailsBody, askQuestionBody, terminalBody, terminalLabels, diffBody, diffLabels, readBody, readLabels, + imageBody, renderSlot, loadImage, searchBody, searchLabels, webBody, webLabels, inspect, t, onOpenFile, + variant, bodyText, cardBody, outputText, state, + ]) return (
{status !== null && {status}} @@ -209,135 +347,10 @@ export function ToolRow({ expandOnRowClick keepContentWhenOpen onToggle={toggleExpand} - collapsedContent={summaryText !== '' && ( - /* An empty summary drops the separator with it (a row that is only - its title shows no trailing dot). */ - <> - - {openFile !== undefined ? ( - - ) : ( - - {summaryText} - - )} - {suffix !== null && ( - {suffix} - )} - - )} + collapsedContent={collapsedContent} > -
- {askQuestionBody !== null - ? - : terminalBody !== null - ? ( - - ) - : diffBody !== null - ? - : readBody !== null - ? - : imageBody !== null - ? ( - /* Label, gallery, then the result's OWN envelope text. The text - comes from the image card model (which reads the result's text - block), never from the row's flattened output: an image read's - content is [text envelope, image block] and flattening - JSON.stringifies the image block, printing the raw attachment - object under the picture. It is not redundant either — the - attachment slot can render nothing, and then this line is the - only evidence an image was returned. */ -
-
{imageBody.label}
- {renderSlot !== undefined && loadImage !== undefined && renderSlot('tool.call.images', { - images: imageBody.images, - loadImage, - align: 'start', - })} -
{imageBody.text}
-
- ) - : searchBody !== null - ? ( - <> - - {/* A capped search's recovery locator lives only in the result - text; show it below the card so the dropped rows survive. */} - {searchBody.recovery !== undefined && ( -
{searchBody.recovery}
- )} - - ) - : webBody !== null - ? - : detailsBody !== null - ? - : ( - <> - {variant === 'code' && bodyText !== null && ( -
- -
- )} - {(cardBody !== null || outputText !== null) && ( -
- {cardBody !== null && ( -
- {t('row.input')} - {cardBody} -
- )} - {cardBody !== null && outputText !== null && ( - - )} - {outputText !== null && ( -
- {t('row.output')} - - {outputText} - -
- )} -
- )} - - )} - {inspect !== undefined && ( - - )} -
+ {expandedContent}
) -} +}) diff --git a/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.tsx b/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.tsx index 37b1d355d0..ebbe18e532 100644 --- a/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.tsx +++ b/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.tsx @@ -1,4 +1,4 @@ -import { useMemo, useState, type KeyboardEvent } from 'react' +import { memo, useCallback, useMemo, useState, type KeyboardEvent } from 'react' import type { Context } from '@deepseek-ai/cordis' import clsx from 'clsx' import { @@ -21,6 +21,8 @@ import css from './bash-sample.module.css' type BashRowProps = ToolCallViewProps & PropsLocale<'conversation'> +const BASH_ICON = + /** Visually hidden status for the color-only running sweep and error tone. */ function stateStatus(state: ToolRowState, t: BashRowProps['t']): string | null { switch (state) { @@ -31,14 +33,19 @@ function stateStatus(state: ToolRowState, t: BashRowProps['t']): string | null { } } -/** Renders expandable Bash output with an accessible lifecycle label. */ -export function BashRow({ toolName, block, sessionId, useSessions, inspect, t }: BashRowProps) { - const model = toolRowModel(toolName, block) +/** + * Render expandable Bash output with an accessible lifecycle label. + * @param props - tool call, Session sources, locale, and inspection callback. + * @returns the Bash output row. + */ +export const BashRow = memo(function BashRow({ toolName, block, sessionId, useSessions, inspect, t }: BashRowProps) { + const model = useMemo(() => toolRowModel(toolName, block), [toolName, block]) // An omitted shell workdir is the session workspace; relative values resolve // against it before reaching the terminal primitive. const cwd = useSessions(list => list.byId[sessionId]?.cwd) - const terminalModel = terminalCardModel(block, cwd) - const terminal = terminalModel === null ? null : localizeTerminalCardModel(terminalModel, t) + const terminalModel = useMemo(() => terminalCardModel(block, cwd), [block, cwd]) + const terminal = useMemo(() => terminalModel === null ? null : localizeTerminalCardModel(terminalModel, t), [terminalModel, t]) + const labels = useMemo(() => terminalBlockLabels(t), [t]) // A failing exit status is the terminal card's own error signal (the call // itself settles isError:false), surfaced through the row's error summary. const state = model.state === 'ok' && terminalModel !== null && terminalFailed(terminalModel) @@ -64,25 +71,24 @@ export function BashRow({ toolName, block, sessionId, useSessions, inspect, t }: ? model.errorSummary ?? normalSummary : state === 'stopped' ? t('bash.stopped') : null const running = state === 'running' - const toggleExpand = () => { + const toggleExpand = useCallback(() => { setExpanded(v => !v) - } - const toggleFromKeyboard = (event: KeyboardEvent) => { + }, []) + const toggleFromKeyboard = useCallback((event: KeyboardEvent) => { if (!expandable || (event.key !== 'Enter' && event.key !== ' ')) return event.preventDefault() toggleExpand() - } - const businessIcon = + }, [expandable, toggleExpand]) const leading = open ? : expandable ? ( <> - {businessIcon} + {BASH_ICON} ) - : businessIcon + : BASH_ICON return (
) @@ -151,7 +157,7 @@ export function BashRow({ toolName, block, sessionId, useSessions, inspect, t }: )}
) -} +}) /** Registers the standalone Bash conversation-row sample. */ export const bashToolviewSample = { From 89ee08b78111c3fe872d8f0dfd500919c5d3448d Mon Sep 17 00:00:00 2001 From: imccyu Date: Sun, 20 Sep 2026 22:29:37 +0800 Subject: [PATCH 22/27] docs: record completed chat migration and deferred turn-step work --- ...26-09-20-chat-work-details-migration.zh.md | 112 +++++++++++------- 1 file changed, 67 insertions(+), 45 deletions(-) diff --git a/.agents/notes/proposed/feature/2026-09-20-chat-work-details-migration.zh.md b/.agents/notes/proposed/feature/2026-09-20-chat-work-details-migration.zh.md index 62381f453e..964d37d9d3 100644 --- a/.agents/notes/proposed/feature/2026-09-20-chat-work-details-migration.zh.md +++ b/.agents/notes/proposed/feature/2026-09-20-chat-work-details-migration.zh.md @@ -4,72 +4,94 @@ Status: proposed ## 问题 -PR #4565 同时包含三档展示设置、过程分组、整轮状态、触发通知、工具行视觉和基础设施行隐藏。整批迁移会把独立功能与列表重组混在一起,也难以逐项判断性能变化。需要一份按功能维护的进度表,先完成不依赖 step-group 的部分,再处理分组,避免遗漏原有产品需求。 +PR #4565 同时包含三档展示设置、过程分组、整轮状态、触发通知、工具行视觉和基础设施行隐藏。整批迁移会把独立功能与列表重组混在一起,也难以逐项判断性能变化。需要一份按功能维护的进度表,先评审独立视觉功能,再结合 step-group 统一考虑轮次相关行为,避免遗漏原有产品需求。 ## 方案 -当前迁移目标是 `feat/chat-presentation-channel`。`pr-4565` worktree 保存原 PR 的重放内容,作为产品行为和实现的参考;`feat/chat-step-groups` 保存尚未接入当前通道的分组实验。不能仅凭分支名或提交记录判断完成情况,还要核对各 worktree 中未提交的代码。 +已完成的独立功能保留在 `feat/chat-presentation-channel`。剩余未完成代码的后续工作区是仓库根目录下的 `.artifacts/worktrees/pr-4565-turnstep`,以当前通道及本进度记录为基线,草稿保持未暂存;后续结合 turn/step 与分组整体评审。`pr-4565` worktree 继续作为原 PR 的行为和实现参考;`feat/chat-step-groups` 的既有分组实验不在本次搬迁范围内。 本记录管理功能范围、当前实现和验收进度。[展示策略通道与过程分组的基础架构](../architecture/2026-09-20-chat-presentation-policy-and-step-groups.zh.md)保留架构路线及备选方案;本记录不替代它,也不把其中的方案视为已经实现。新记录没有完整取代既有架构决策,因此保留原记录,不做归档或删除。 -本记录处于开发阶段,只维护中文版。新增迁移代码不自动暂存,不覆盖已有暂存内容。当前这一轮仅新增本记录,没有继续迁移功能代码。 +本记录处于开发阶段,只维护中文版。完成状态、实现状态、暂存或提交状态、验收状态分别记录。未完成项即使已有代码草稿,也继续标为未完成,不从清单移除。测试断言、README 和录制快照留待后续;代码写好、进入暂存区、提交或构建通过,都不等同于功能或性能验收。 ### 状态定义 -| 状态 | 含义 | -|---|---| -| 当前代码已有 | 已能在当前 worktree 源码中找到实现;不代表已提交、已发布或通过完整验收 | -| 待迁移 | 已纳入非分组迁移范围,当前尚未实现 | -| 分组阶段 | 产品需求保留,依赖分组结构或分组交互,暂不接入当前通道 | -| 待验收 | 需要行为、节点身份、刷新范围或浏览器性能证据;不能用编译结果代替 | +| 维度 | 状态 | 含义 | +|---|---|---| +| 完成 | 已完成 | 功能迁移代码已逐项审阅并提交到当前通道;行为与性能证据另行记录 | +| 完成 | 未完成 | 尚未纳入当前通道的已完成迁移范围;可以已有未暂存草稿,也可以尚未编写 | +| 实现 | 当前代码已有 | 当前通道的既有基础能力 | +| 实现 | 代码已写好 | 对应工作区中已有实现;不代表已完成、已暂存、已提交或通过验收 | +| 实现 | 待迁移 | 已纳入非分组迁移范围,当前尚未实现 | +| 实现 | 分组阶段 | 产品需求保留,依赖分组结构或分组交互,暂不接入当前通道 | +| 暂存或提交 | 未暂存 | 该功能的改动仍在工作区,包括尚未跟踪的新文件 | +| 暂存或提交 | 部分暂存 | 该功能只有部分改动进入暂存区,必须注明具体范围 | +| 暂存或提交 | 已暂存 | 该功能当前待提交的代码改动均已进入暂存区,尚未提交 | +| 暂存或提交 | 已提交 | 该功能代码已包含在当前 HEAD 中 | +| 验收 | 待验收 | 需要行为、节点身份、刷新范围或浏览器性能证据;不能用 Git 状态或编译结果代替 | + +暂存状态按产品功能对应的差异片段核对,不按整个文件推断。更新状态时同时查看工作区、暂存区和 HEAD;共享文件只暂存部分字段,不能将依赖该文件的所有功能都标为已暂存。 ### 当前通道已有的能力 -| 能力 | compact | detailed | expanded | 实现状态 | 验收状态 | -|---|---|---|---|---|---| -| 三档设置与旧值读取 | 简洁 | 详细;旧值 `normal` 读作本档,不回写 | 完全展开 | 当前代码已有 | 待验收 | -| 按轮判断整轮折叠资格 | 本轮已结束、起点已加载且存在最终答案时可折叠 | 相同 | 相同 | 当前代码已有 | 待验收 | -| 已完成推理的收起摘要 | 只显示「思考」 | 显示首行 | 显示首行 | 当前代码已有 | 待验收 | -| 模式切换时保留摘要 DOM | 用 CSS 隐藏摘要及分隔点 | 显示原有摘要及分隔点 | 相同 | 当前代码已有 | 待验收 | -| 推理预览的局部订阅 | `ReasoningRow` 选择自己的可见性 | 相同 | 相同 | 当前代码已有 | 待验收 | -| 折叠行引用稳定 | 回调、图标及未变化的摘要保持引用;完整 Markdown 仅在展开时挂载 | 相同 | 相同 | 当前代码已有 | 待验收 | +| 能力 | compact | detailed | expanded | 完成状态 | 实现状态 | 暂存或提交状态 | 验收状态 | +|---|---|---|---|---|---|---|---| +| 三档设置与旧值读取 | 简洁 | 详细;旧值 `normal` 读作本档,不回写 | 完全展开 | 已完成 | 当前代码已有 | 已提交 | 待验收 | +| 按轮判断整轮折叠资格 | 已加载起点且存在最终回复的结束轮次,可收起过程内容;停止和失败的扩展行为见迁移项 6 | 相同 | 相同 | 已完成 | 当前代码已有 | 已提交 | 待验收 | +| 已完成推理的收起摘要 | 只显示「思考」 | 显示首行 | 显示首行 | 已完成 | 当前代码已有 | 已提交 | 待验收 | +| 模式切换时保留摘要 DOM | 用 CSS 隐藏摘要及分隔点 | 显示原有摘要及分隔点 | 相同 | 已完成 | 当前代码已有 | 已提交 | 待验收 | +| 推理预览的局部订阅 | `ReasoningRow` 选择自己的可见性 | 相同 | 相同 | 已完成 | 当前代码已有 | 已提交 | 待验收 | +| 折叠行引用稳定 | 回调、图标及未变化的摘要保持引用;完整 Markdown 仅在展开时挂载 | 相同 | 相同 | 已完成 | 当前代码已有 | 已提交 | 待验收 | 三档都保留整轮折叠。`expanded` 的产品含义是取消二级过程分组,并非禁止整轮折叠,也不是自动展开每个思考或工具卡的正文。分组尚未接入时,`detailed` 与 `expanded` 的 Chat 展示相同。 ### 不依赖分组的迁移清单 -下表的“三档共用”表示三档都应用该行为,不表示切换档位时会改变它。 +下表的“三档共用”表示三档都应用该行为,不表示切换档位时会改变它。“不依赖分组”指实现草稿未引入 step-group,不代表都要先于分组接受。编号沿用逐项评审清单;编号 0 的编译接线修正已完成并提交,不作为产品功能另列。未完成项的草稿留在 `pr-4565-turnstep`,不是当前通道已完成的功能。下列功能的行为与性能均待验收。 -| 功能 | compact | detailed | expanded | 当前状态 | 迁移落点与注意事项 | -|---|---|---|---|---|---| -| 流式推理摘要 | 段落首行写完后才更新 | 相同 | 相同 | 待迁移 | 保留现有摘要 DOM 和局部订阅;配套右侧渐隐。当前仍跟随最新一行,不能标为完成。原版每次扫描全文的计算方式需要优化 | -| 工具标题中文化 | 三档共用 | 三档共用 | 三档共用 | 待迁移 | Bash/Pwsh 为「运行命令」、Grep 为「搜索文件内容」、Glob 为「查找文件」、Skill 为「加载技能」;只改 UI 字典,不改模型工具名 | -| 工具行交互视觉 | 三档共用 | 三档共用 | 三档共用 | 待迁移 | 悬停时标题和摘要加深,展开箭头朝上;共享 `DisclosureRow` 的调用方一并核对 | -| Bash 停止状态的读屏提示 | 三档共用 | 三档共用 | 三档共用 | 待迁移 | 补齐停止状态的可访问名称,不改变执行或取消语义 | -| 工具及命令运行时文字扫光 | 三档共用 | 三档共用 | 三档共用 | 待迁移 | 保留固定文本节点,以运行状态控制动画;不把新建 ReactNode 和临时回调重新引入 memo 调用链;保留减少动态效果设置 | -| 取消、失败后保持过程展开 | 三档共用 | 三档共用 | 三档共用 | 待迁移 | 已停止和失败的轮次不自动收起,也不允许手动收起;可独立于计时控件迁移 | -| 整轮状态与用时控件 | 三档共用 | 三档共用 | 三档共用 | 待迁移 | 从轮次开始显示,运行时显示用时,完成后固定时长,停止或失败显示对应状态;移除底部重复运行条。控件提前出现需要处理锚点和排序,但不需要 step-group | -| 非人工触发通知 | 三档共用 | 三档共用 | 三档共用 | 待迁移 | 用持久化 Inbox 领取记录识别唤醒输入,显示独立通知;展开查看原始内容。来源标题仅使用已记录的来源字段,不解析正文猜测身份 | -| 隐藏基础设施行 | 三档共用 | 三档共用 | 三档共用 | 待迁移 | Chat 隐藏系统提示词、普通上下文注入和 permission 命令;Session 数据及 Trajectory 保留。先保住唤醒通知,再隐藏普通上下文;可见性在节点定义处集中决定 | -| 轮次操作栏位置 | 三档共用 | 三档共用 | 三档共用 | 待迁移 | 操作栏放到轮次结束之后,反馈仍对应最后一条持久化文字回复;检查中断、重试和分支操作,不直接删除相关判定 | -| 操作栏常显条件 | 三档共用 | 三档共用 | 三档共用 | 待迁移 | 最新轮仅在最后可见内容为回复时常显,其余通过悬停或键盘聚焦显示;把判定放回 Turn 自己的投影,不引入原版分组索引 | +| 编号 | 功能 | compact | detailed | expanded | 完成状态 | 实现状态 | 暂存或提交状态 | 迁移落点与注意事项 | +|---|---|---|---|---|---|---|---|---| +| 1 | 工具标题中文化 | 三档共用 | 三档共用 | 三档共用 | 已完成 | 代码已写好 | 已提交 | Bash/Pwsh 为「运行命令」、Grep 为「搜索文件内容」、Glob 为「查找文件」、Skill 为「加载技能」;只改 UI 字典,不改模型工具名 | +| 2 | 工具行交互视觉 | 三档共用 | 三档共用 | 三档共用 | 已完成 | 代码已写好 | 已提交 | 工具行、Bash 行和命令行悬停时标题及摘要加深;共享 `DisclosureRow` 和独立 Bash 行展开箭头朝上 | +| 3 | Bash 停止状态的读屏提示 | 三档共用 | 三档共用 | 三档共用 | 已完成 | 代码已写好 | 已提交 | 补齐停止状态的可访问名称,不改变执行或取消语义 | +| 4 | 工具及命令运行时文字扫光 | 三档共用 | 三档共用 | 三档共用 | 已完成 | 代码已写好 | 4A 扫光与 4B 附带优化均已提交 | 4A 包含 `TextShimmer` 固定 span 与 CSS 启停、工具及命令行接入、旧扫光样式替换和减少动态效果支持,不含 step/turn;4B 为业务行额外的计算缓存、稳定回调及 JSX 引用 | +| 5 | 流式推理摘要 | 段落首行写完后才更新 | 相同 | 相同 | 已完成 | 代码已写好 | 已提交 | `ReasoningRow` 沿用原 PR 的 `latestCompletedParagraphFirstLine(text)`,直接从完整文本计算;摘要 DOM、稳定 props 和右侧渐隐保留,不增加 Definition 解析状态或跨层摘要字段 | +| 6 | 取消、失败后保持过程展开 | 三档共用 | 三档共用 | 三档共用 | 未完成 | 代码草稿已写好 | 未暂存 | 草稿在 Turn 过程投影中使用 `keepOpen`;轮次与分组阶段再评审折叠资格和停止、失败行为 | +| 7 | 整轮状态与用时控件 | 三档共用 | 三档共用 | 三档共用 | 未完成 | 代码草稿已写好 | 未暂存 | 草稿将控件锚定到已加载的 `turn/start`、排在开场输入之后,以 `LiveTurnProcessLabel` 单独计时,并替换底部运行条;整体定位与状态待评审 | +| 8 | 非人工触发通知 | 三档共用 | 三档共用 | 三档共用 | 未完成 | 代码草稿已写好 | 未暂存 | 草稿使用 next-turn 及首步 next-step 领取事实识别唤醒输入,投影 `turn-trigger`;轮次起点、通知归属和展开内容待评审 | +| 9(permission/系统) | 隐藏 permission 命令与系统提示词行 | 三档共用 | 三档共用 | 三档共用 | 已完成 | 代码已写好 | 已提交 | `isVisibleChatNode` 集中判断,现有 Chat 列表、导航和过程展示复用;命令与请求提示词 Definition 不承载这些过滤规则,持久化数据与 Trajectory 不变 | +| 9(context) | 隐藏普通上下文行 | 三档共用 | 三档共用 | 三档共用 | 未完成 | 代码草稿已写好 | 未暂存 | 与 8 的唤醒通知配套,保留来源解释;过滤规则的最终归属留到轮次与分组阶段 | +| 10 | 轮次操作栏位置 | 三档共用 | 三档共用 | 三档共用 | 未完成 | 代码草稿已写好 | 未暂存 | 草稿将 `turn-tail` 锚定到 `turn/end` 之后;反馈、复制的回复归属和分支的真实轮次结束序号待整体评审 | +| 11 | 操作栏常显条件 | 三档共用 | 三档共用 | 三档共用 | 未完成 | 代码草稿已写好 | 未暂存 | 草稿由 Chat builder 按 Turn 投影 `footer`;最新轮以回复结尾时常显,其余悬停或聚焦显示,尾部判定与分组一起考虑 | 开发者工具默认开启已由当前基线提供,不重复迁移。当前实现保留等待 Host 接受设置后才启用相关能力的保护,不以原 PR 的缺值回退覆盖它。原 PR 的 `Switch` 改动只有注释,不作为功能迁移项。 +### 后续评审批次 + +评审批次独立于实现和暂存状态。未完成草稿的后续评审统一在 `pr-4565-turnstep`,保持未暂存;已有草稿不代表迁移已完成。仅搬迁当前通道的剩余代码,不自动合入 `feat/chat-step-groups` 的实验,也不在目标工作区安装依赖或编译。 + +| 批次 | 功能 | 评审范围 | +|---|---|---| +| 独立功能,已提交 | 4A:文字扫光 | `TextShimmer` 本身、各行的调用方式和浏览器绘制成本;性能待验收 | +| 独立优化,已提交 | 4B:附带的 memo 与引用稳定化 | `ToolRow`、`BashRow` 和 `GenericCommandCard` 的计算缓存、回调和 JSX 引用;不是扫光功能的必要条件,性能待验收 | +| 独立功能,已提交 | 9 中的 permission 命令与系统提示词隐藏 | 沿用原 PR 的集中可见性判断;当前无 step-group,主列表改在 `orderedVisibleChatNodes` 接入,不依赖唤醒消息分类 | +| 未完成,转入 turnstep 工作区 | 6、7、10、11 | 整轮折叠资格、状态与时钟、操作栏位置和尾部判定,统一考虑轮次与分组关系 | +| 未完成,转入 turnstep 工作区 | 8、9 中的普通 context 隐藏 | 触发通知依赖轮次起点和 Inbox 领取判定;隐藏普通上下文与通知配套,避免先隐藏唤醒原因 | + ### 分组阶段保留的需求 -这些项目当前均未接入 `feat/chat-presentation-channel`。隔壁 worktree 有实验代码,不代表这些产品行为或性能要求已经完成。 +这些项目均未完成,继续保留全部需求,后续在 turn/step 与分组阶段处理。当前通道和本次搬迁草稿均未引入 step-group;`feat/chat-step-groups` 的实验代码不代表这些产品行为或性能要求已经完成。 | 功能 | compact | detailed | expanded | 当前状态 | |---|---|---|---|---| -| 回复之间的连续过程分组 | 工具与推理归组,默认收起 | 相同 | 过程行直接展示,不使用二级分组包装 | 分组阶段 | -| 同一 Assistant 中推理与回复的分别显隐 | 推理可归入前组,回复外露 | 相同 | 不做二级分组隐藏 | 分组阶段;不直接复制原版拆成两个渲染节点的实现 | -| 组头类别摘要 | 运行时显示当前类别,完成后聚合主要类别 | 相同 | 无组头 | 分组阶段 | -| 运行中组头详情 | 不显示 | 显示命令、路径、查询等详情,无运行工具时显示推理摘要 | 无组头 | 分组阶段 | -| 组头内容更新节奏 | 保留类别标题的最短展示时间 | 同时处理详情更新 | 不适用 | 分组阶段 | -| 组内限高滚动 | 展开内容限高、独立滚动、边缘渐隐 | 相同 | 不适用 | 分组阶段 | -| 分组与整轮折叠联动 | 整轮收起时隐藏分组 | 相同 | 仅整轮折叠 | 分组阶段;保留节点身份,内部开合状态是否重置单独确定 | -| 分页、流式结算与组身份 | 既有组头和成员稳定,半截轮单独处理 | 相同 | 同一批业务节点直接展示 | 分组阶段 | +| 回复之间的连续过程分组 | 工具与推理归组,默认收起 | 相同 | 过程行直接展示,不使用二级分组包装 | 未完成(分组阶段) | +| 同一 Assistant 中推理与回复的分别显隐 | 推理可归入前组,回复外露 | 相同 | 不做二级分组隐藏 | 未完成;不直接复制原版拆成两个渲染节点的实现 | +| 组头类别摘要 | 运行时显示当前类别,完成后聚合主要类别 | 相同 | 无组头 | 未完成(分组阶段) | +| 运行中组头详情 | 不显示 | 显示命令、路径、查询等详情,无运行工具时显示推理摘要 | 无组头 | 未完成(分组阶段) | +| 组头内容更新节奏 | 保留类别标题的最短展示时间 | 同时处理详情更新 | 不适用 | 未完成(分组阶段) | +| 组内限高滚动 | 展开内容限高、独立滚动、边缘渐隐 | 相同 | 不适用 | 未完成(分组阶段) | +| 分组与整轮折叠联动 | 整轮收起时隐藏分组 | 相同 | 仅整轮折叠 | 未完成;保留节点身份,内部开合状态是否重置单独确定 | +| 分页、流式结算与组身份 | 既有组头和成员稳定,半截轮单独处理 | 相同 | 同一批业务节点直接展示 | 未完成(分组阶段) | 分组产品细节的核对项:完成摘要最多聚合前三类,超过三类使用「等」;调用计数用于分类排序,不直接显示为组头数字。详细模式的实时详情合并空白并限制为 160 个字符;标题最短展示时间为 150ms,只保留最新更新,不补播积压项。展开区高度不超过 400px 与半屏中的较小值,可滚动方向显示 24px 渐隐,并保留与外层滚动的衔接。重试行不属于二级过程组。这些数值是原 PR 的行为参考,不代表当前分组实验已经实现。 @@ -78,7 +100,7 @@ PR #4565 同时包含三档展示设置、过程分组、整轮状态、触发 | 场景 | 要保留的性质 | 所需证据 | |---|---|---| | 切换三档模式 | 不改变业务节点 key,不因模式切换重新注册 Definition;仅相关可见性或展示字段更新 | 节点身份和刷新范围检查 | -| 推理或工具内容增量更新 | 只更新所属节点;避免每个分片重新扫描完整推理或完整历史 | 增量工作量与长内容场景 | +| 推理或工具内容增量更新 | 只更新所属节点,不扫描完整历史;推理摘要在渲染时从当前完整文本计算 | 更新范围与长内容计算开销;当前摘要算法不减少 `ReasoningRow` 的渲染次数 | | 整轮运行时钟 | 只有运行中的时钟内容按秒更新,不带动整轮成员、历史行和列表 | 更新范围及计时器释放检查 | | 摘要显隐 | 轻量摘要常驻;完整 Markdown 正文不为模式切换而全部常驻 | DOM 身份、首次加载和内存观察 | | 分页 | 新增节点与事实变化的节点更新,已完成轮次不因全局分页状态一起刷新 | 多页历史交互与刷新范围检查 | @@ -98,18 +120,18 @@ PR #4565 同时包含三档展示设置、过程分组、整轮状态、触发 ## 验收标准 -完成一项时更新它的实现状态、实际落点和验证记录;未完成项保留,不因拆分分支而删除。分组阶段开始前,逐行复核上面的产品需求和模式对应关系。 +每项代码写好、暂存或提交后,分别更新对应状态;完成状态按逐项评审和提交记录更新,验收只按实际验证记录更新。未完成项保留,不因拆分分支或搬迁工作区而删除。分组阶段开始前,逐行复核上面的产品需求和模式对应关系。 | 验收项 | 当前状态 | |---|---| | 当前通道已有能力的完整行为验证 | 待验收;既有测试包含只做类型接线、尚未调整的旧断言 | -| 非分组功能迁移 | 待迁移;本次仅创建进度记录 | +| 非分组功能迁移 | 完成范围见迁移清单;未完成草稿留到 `pr-4565-turnstep` 继续评审,功能与性能验证仍未完成 | | 模式切换时的 DOM 身份和刷新范围 | 待验收;不能以 memo 或 selector 的存在代替实际证据 | | 长会话首次打开、分页、流式输入与内存 | 待验收;原 PR 的历史测量不代表本实现 | | 新行为的单元、浏览器与录制快照覆盖 | 待补;开发阶段不在此轮运行测试或录制 | -| 分组功能与两档差异 | 分组阶段 | +| 分组功能与两档差异 | 未完成(分组阶段) | -此前通道调整有编译检查记录,但不是本次全部迁移的通过证明,也不代表当前所有测试通过。本轮未执行检查。 +历史构建记录:迁移草稿曾通过三个源码包的单独 TypeScript 构建和完整 `pnpm run build`。首轮构建暴露的展示策略辅助文件编译归属问题已修正并提交,没有调整测试断言。该记录不代表拆分后的当前通道或 turnstep 工作区已重新验证;本次仅提交进度记录并搬迁草稿,不安装依赖、不编译、不执行测试、快照或性能基准。 ## 风险 From f1c035b1e9d6b91e00c58975b77e9b49a3f5c4e7 Mon Sep 17 00:00:00 2001 From: imccyu Date: Sun, 20 Sep 2026 23:20:07 +0800 Subject: [PATCH 23/27] test(chat): align presentation coverage and snapshots --- ...sentation-policy-and-step-groups.i18n.yaml | 6 + ...hat-presentation-policy-and-step-groups.md | 286 ++++++++++++++++++ ...-presentation-policy-and-step-groups.zh.md | 22 +- ...9-20-chat-work-details-migration.i18n.yaml | 6 + .../2026-09-20-chat-work-details-migration.md | 144 +++++++++ ...26-09-20-chat-work-details-migration.zh.md | 12 +- .../tests/chat-continuous-conversation.e2e.ts | 4 +- .../expected/cordis-history/ui.expected.md | 9 +- .../expected/fork-mid-turn/ui.expected.md | 4 +- .../conversation-expanded.expected.md | 1 - .../conversation.expected.md | 1 - .../settings-chrome/dialog-en.expected.md | 2 +- .../dialog-no-browser.expected.md | 2 +- .../settings-chrome/dialog.expected.md | 4 +- .../skill-user-invoke/ui-expanded.expected.md | 1 - .../expected/skill-user-invoke/ui.expected.md | 1 - .../expected/steer-all/mid-steer.expected.md | 3 +- .../steer-all/settled-expanded.expected.md | 3 +- .../expected/steer-all/settled.expected.md | 1 - apps/web/tests/goal-multi-turn-actions.e2e.ts | 4 +- apps/web/tests/lifecycle-chrome.e2e.ts | 17 +- apps/web/tests/message-actions.e2e.ts | 6 +- apps/web/tests/replay-round-trip.e2e.ts | 21 +- apps/web/tests/seeded-history.e2e.ts | 21 +- apps/web/tests/settings-chrome.e2e.ts | 24 +- apps/web/tests/turn-tail-actions.e2e.ts | 19 +- .../ui-chat/tests/chat-view.client.spec.tsx | 78 +++-- ...nversation-node-definitions.client.spec.ts | 99 +++--- .../tests/presentation-policy.client.spec.tsx | 64 ++++ .../tests/reasoning-row.client.spec.tsx | 93 +++++- .../tests/transcript-view-row.client.spec.tsx | 31 +- .../tests/text-shimmer-styles.client.spec.ts | 16 + .../tests/text-shimmer.client.spec.tsx | 29 ++ .../tests/browser-plugin.client.spec.ts | 2 +- .../ui-skill/tests/skill-row.client.spec.tsx | 6 +- .../tests/coverage-tails.client.spec.tsx | 13 +- .../ui-tool/tests/search-card.client.spec.tsx | 4 +- .../ui-tool/tests/tool-row.client.spec.tsx | 12 +- .../src/client/slot-catalog.ts | 10 +- snapshots/web/bash-abort-row/ui.expected.md | 1 - .../web/changed-files-turn/ui.expected.md | 11 +- .../web/deepseek-messages-chat/ui.expected.md | 1 - .../web/default-workspace/ui.expected.md | 1 - .../feedback-command/ack-expanded.expected.md | 3 +- .../web/feedback-command/ack.expected.md | 1 - .../feedback-release/ack-expanded.expected.md | 3 +- .../web/feedback-release/ack.expected.md | 1 - .../web/file-upload-round/ui.expected.md | 1 - .../fresh-round-trip/ui-expanded.expected.md | 5 +- snapshots/web/fresh-round-trip/ui.expected.md | 1 - .../ui-expanded.expected.md | 20 +- .../goal-multi-turn-actions/ui.expected.md | 2 - .../reloaded-expanded.expected.md | 3 +- .../web/lifecycle-chrome/reloaded.expected.md | 1 - .../cancel-expanded.expected.md | 1 - .../web/live-interactions/cancel.expected.md | 1 - .../live-interactions/error-auth.expected.md | 1 - .../web/live-interactions/loading.expected.md | 1 - .../retry-exhausted.expected.md | 1 - .../retry-expanded.expected.md | 3 +- .../web/live-interactions/retry.expected.md | 1 - .../running-draft.expected.md | 1 - snapshots/web/message-actions/ui.expected.md | 4 +- snapshots/web/minimal-preset/ui.expected.md | 1 - .../plan-review/approved-expanded.expected.md | 9 +- .../web/plan-review/approved.expected.md | 5 +- snapshots/web/present-svg/ui.expected.md | 5 +- snapshots/web/present/ui.expected.md | 5 +- snapshots/web/ptc-round/ui.expected.md | 5 +- .../answered-expanded.expected.md | 5 +- .../question-composer/answered.expected.md | 1 - .../question-composer/cancelled.expected.md | 3 +- .../web/queue-actions/collapsed.expected.md | 1 - .../web/queue-actions/editing.expected.md | 1 - .../web/queue-actions/layout.expected.md | 1 - .../preserved-expanded.expected.md | 1 - .../web/queue-actions/preserved.expected.md | 1 - .../web/queue-actions/sending.expected.md | 1 - snapshots/web/queue-actions/ui.expected.md | 1 - .../web/queued-image/delivered.expected.md | 1 - snapshots/web/queued-image/queued.expected.md | 1 - .../seeded-history/command-row.expected.md | 6 +- .../seeded-history/feedback-row.expected.md | 6 +- .../seeded-history/ui-expanded.expected.md | 5 +- snapshots/web/seeded-history/ui.expected.md | 1 - snapshots/web/skill-tool-row/ui.expected.md | 5 +- snapshots/web/steering/mid-steer.expected.md | 1 - .../web/steering/settled-expanded.expected.md | 1 - snapshots/web/steering/settled.expected.md | 1 - .../sidebar-chat.expected.md | 1 - .../ui-expanded.expected.md | 9 +- .../web/subagent-conversation/ui.expected.md | 5 +- .../offline-composer.expected.md | 1 - .../turn-tail-actions/completed.expected.md | 1 - .../web/turn-tail-actions/focused.expected.md | 3 +- .../web/turn-tail-actions/running.expected.md | 3 +- .../web/turn-tail-actions/settled.expected.md | 1 - .../usage-expanded.expected.md | 1 - snapshots/web/web-search-round/ui.expected.md | 1 - snapshots/web/workflow-run/ui.expected.md | 5 +- 100 files changed, 932 insertions(+), 323 deletions(-) create mode 100644 .agents/notes/proposed/architecture/2026-09-20-chat-presentation-policy-and-step-groups.i18n.yaml create mode 100644 .agents/notes/proposed/architecture/2026-09-20-chat-presentation-policy-and-step-groups.md create mode 100644 .agents/notes/proposed/feature/2026-09-20-chat-work-details-migration.i18n.yaml create mode 100644 .agents/notes/proposed/feature/2026-09-20-chat-work-details-migration.md create mode 100644 packages/client/ui-chat/tests/presentation-policy.client.spec.tsx create mode 100644 packages/client/ui-primitives/tests/text-shimmer-styles.client.spec.ts create mode 100644 packages/client/ui-primitives/tests/text-shimmer.client.spec.tsx diff --git a/.agents/notes/proposed/architecture/2026-09-20-chat-presentation-policy-and-step-groups.i18n.yaml b/.agents/notes/proposed/architecture/2026-09-20-chat-presentation-policy-and-step-groups.i18n.yaml new file mode 100644 index 0000000000..bb3a7b1cbe --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-09-20-chat-presentation-policy-and-step-groups.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/proposed/architecture/2026-09-20-chat-presentation-policy-and-step-groups.md +2026-09-20-chat-presentation-policy-and-step-groups.md: df0397a0568967c920994192b370e9fe1d063229 +2026-09-20-chat-presentation-policy-and-step-groups.zh.md: 1bf9cf95174a1de0c7d0576bdd9fbb842d980ae7 diff --git a/.agents/notes/proposed/architecture/2026-09-20-chat-presentation-policy-and-step-groups.md b/.agents/notes/proposed/architecture/2026-09-20-chat-presentation-policy-and-step-groups.md new file mode 100644 index 0000000000..df0397a056 --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-09-20-chat-presentation-policy-and-step-groups.md @@ -0,0 +1,286 @@ +# Agent Note: Chat presentation policy channel and process-group architecture + +Status: proposed + +English | [中文](2026-09-20-chat-presentation-policy-and-step-groups.zh.md) + +## Problem + +At the start of this proposal, Chat's display setting had two modes: `normal` did not fold content, while `compact` folded process rows behind a whole-Turn control after completion. `TranscriptViewPolicy.mode` was injected into ChatView as an observable. ChatView read it through `useTranscriptView`, converted it to the boolean `compactTranscript`, and passed that prop through `ChatNodeList` to every `ChatNodeSeat`. The global `hasMore` boolean followed the same path as `historyIncomplete`. Either change re-rendered every seat, even when only a few foldable rows changed their output. + +The product requires three modes—Compact, Detailed, and Expanded—with consecutive process rows between replies collected into collapsible groups in Compact and Detailed. PR #4565 implemented the full feature, but was reverted eight minutes after merging because of performance regressions. The recorded local before/after comparison found long-session pagination +27%, DOM nodes +23%, heap +14%, and Trajectory switching +10%, all within CI budgets. None of the six existing repository benchmarks covered the new hot path: reasoning or tool chunks entering an active group during streaming, group reprojection, and seat re-rendering. + +The review identified implementation choices, not the product requirements, as the problem: + +- The mode became an input to list structure. `ChatNodeList` subscribed to the entire `layout` and generated wrapper components from ranges; Expanded removed those wrappers. Switching modes remounted the list, and regrouping rebuilt wrapper keys. +- The mode entered `ChatNodeOwnerProps`. Every seat's owner object changed with the mode, re-rendering all business renderers, including unrelated user messages, tool rows, and compaction markers. +- A seat split one Assistant node into derived reasoning and response objects solely to wrap the former in the DOM. Master's `AssistantMarkdown` already had `reasoningHidden` and `revealProcess`, which could hide reasoning independently. +- Consumers repeated infrastructure-row filtering in four places, although nodes already had a Definition-owned `visibility` field. + +The deeper difficulty is information ownership: a group header must exist before its members as soon as the group opens, but its content requires a view of the entire Turn. Each event-driven Context receives only its own events. Only a turn-level Context can observe the whole Turn, and it can produce only one node. + +This proposal supplies an architecture for three modes and grouping that satisfies the constraints below and confines later product changes to a small set of nodes. + +The three settings, presentation policy channel, and per-Turn folding eligibility are implemented; step-group remains proposed. The [migration progress table](../feature/2026-09-20-chat-work-details-migration.md) owns current implementation, committed scope, and incomplete items. The grouping state machine and change inventory below do not describe delivered work. + +## Goals and constraints + +The following decisions were confirmed during design review and are inputs to this proposal. + +| Number | Decision | Meaning | +|---|---|---| +| 1 | Definitions own group structure | A Definition matching multiple events in the Turn folds group opening, closing, member ranges, and summaries; renderers do not derive them by scanning nodes | +| 2 | Limit seat re-rendering | Mode changes re-render only seats whose presentation changes; streaming chunks re-render only their seat and group header; user messages, replies, and turn-tail do not re-render for either change | +| 3 | One node per Context | Do not introduce multiple nodes per Context; most Contexts have one element, and arrays would fragment memory further | +| 4 | Modes do not toggle Definitions | Registry changes rebuild and replay all Contexts, refreshing every seat; Definitions must be mode-independent | +| 5 | Decide folding per Turn | A Turn can fold when its own `turn/start` is loaded; the oldest partial Turn stays open and is not optimized here | +| 6 | ui-conversation may change | Engine changes are allowed only where needed for this design to work correctly | +| 7 | Initial implementation scope | Initially change only code and this note; add tests and other documentation during CI repair | + +Accepting a full-page browser layout on mode changes does not mean accepting every seat re-rendering. Layout is a geometric result; a seat re-render executes a React component function. This proposal constrains the latter. + +## Viable approaches + +There are five approaches to group-header identity and content ownership. + +**Approach A: the first member's seat renders the header.** Keep the list unchanged. The builder derives membership and tells the first member's seat to render a title above itself; other member seats use the existing `hidden` mechanism. This adds no new concept, but creates a third seat state—visible with only a title—and attaches the header to a business node's seat. + +**Approach α: one Context per step supplies a header.** Add a Definition identified by `turn:step`. During construction, read the preceding `assistant-step` data to decide whether this is a new group start and emit a header node if so. Another turn-level Definition publishes the group's content as Turn data for the renderer. + +**Approach β: one Context emits multiple nodes.** A turn-level Definition emits the whole-Turn control and N group headers. + +**Approach γ: a parent Context derives child Contexts.** When a group opens, the turn-level fold creates a `step-group` child Context and forwards later events to it. Each child owns one node. The engine needs forwarding and cascaded replay primitives. + +**Approach δ: Definitions own structure; the builder materializes rows.** A turn-level Definition folds the group list and publishes Turn data. The Chat builder materializes header nodes and assigns membership. Seats use combined selectors for visibility. `ViewBuilder.apply` receives the Location data whose references changed in the flush. + +## Alternatives considered + +**One Context per group cannot satisfy the matching rules.** The engine requires `match(event)` to derive an id from one event. A group number depends on whether a reply preceded the event; one event cannot determine it. This is incompatible with the matching contract, not merely difficult to implement. + +**Approach α conflicts with decision 2.** Header identity is derivable, but every header reads the same Turn data, so one group's change refreshes all headers in that Turn. Reading later steps through `turn.steps` instead leaves stale references because a header node is not rebuilt when later steps arrive. + +**Decision 3 rules out approach β.** See the table above. + +**Approach γ is not justified yet.** It has the clearest ownership, but forwarding and cascaded replay would add hundreds of lines to the assembler core. It remains an alternative under the conditions at the end of this note. + +**Approach A remains the fallback.** If builder-owned materialization is rejected in practice, use A. Both share the same structural source and differ only in what carries the header row. + +Choose approach δ. + +## Proposal + +### Data flow + +``` +事件流 + ──▶ step-groups Definition(turn 级 fold,多重匹配本轮事件) + ──▶ Turn 数据 step-groups:组列表,每组一个对象 + ──▶ Chat builder + ├─ 物化组头节点:一组一个 key,data 即组对象 + └─ 成员归属:按 step 映射到 key,写进 per-key presentation + ──▶ seat:hidden = f(策略字段, 角色, 展开状态) + ──▶ 组头渲染器:读自己节点的 data +展示策略 + ──▶ 渲染器:按 kind 注入的 hooks,选单个字段 + ──▶ seat:组合 selector,选出的是自己的结论 +``` + +The only engine change passes the Location data whose references changed during a flush to the builder through `apply`. + +### Responsibilities + +| Layer | Owns | Explicitly does not own | +|---|---|---| +| `step-groups` Definition | Opening and closing groups, `headStep`, `closeStep`, tool counts and names, running tools; publishes Turn data | View nodes or identification of member nodes | +| Chat builder | Header-node identity and lifecycle, membership, `turnStarted`, identity comparison and publication of per-key presentation | Reading events or deriving business structure | +| Presentation policy object | Mapping the enum to capability fields | Node or seat state | +| Seat | Combining policy fields, role, and store state into hidden state; supplying group open/close actions to the header renderer | Determining group boundaries | +| Header renderer | Title, chevron, click-to-toggle interaction | The source of group content | +| assistant-step renderer | Settled reasoning first-line preview; hiding reasoning when closing a group | Group boundaries | + +### Header-node identity and lifecycle + +A header node's key is `step-group:${turn}:${headStep}`. `headStep` is fixed when a group opens, and later events cannot change its first member. The header exists and is reused from that point onward; its key does not change during streaming. Closing the group only changes `closed` in its data from false to true. + +The header anchor is the first member's anchor minus a synthetic offset, placing it immediately before that member. A streaming Assistant is anchored at its first visible chunk, then at its message event after persistence. Its anchor moves once; the header follows in the same structural update without adding another update. + +A header is part of the whole-Turn process and hides with its members when the Turn folds. It is not in `TURN_PROCESS_INDEPENDENT_KINDS`. + +Header data is the group object published by the fold. Closed group objects never change references, so their header sources never notify. Each event that changes a running group replaces only that group's object and re-renders only its header. + +### Fold state machine + +The `step-groups` Definition uses the Turn number as its id, starts on `turn/start`, and matches the same event set as `turn-process`. Its State is `{ turn, groups, open }`: `groups` is an array of group objects, and `open` is the active group's index or empty. + +| Event | Transition | +|---|---| +| `tool/call` | If no group is open, open one at the event's step; increment the count, record distinct tool names, and add callId to the running set | +| Appended `tool/result` | Remove callId from the running set | +| `assistant/live-chunk` reasoning delta with visible characters | Open a group at the chunk's step if none is open | +| `assistant/live-chunk` text delta or text-block end with visible characters | Close an open group at the chunk's step | +| Appended `assistant/message` | Apply the reasoning rule for visible reasoning and the text rule for a visible reply, in reasoning-then-text order | +| `turn/end` | Mark an open group as closed by the Turn end | +| `step/start`, `step/end`, `llm/retry` | No state change; retry rows belong to no group | + +Three invariants apply: + +- Idempotence: opening an already-open group and closing an already-closed group do nothing. Live chunks and persisted messages describing the same content do not open or close twice; replay with only persisted messages derives the same group list. +- Stable references: `update` returns the original object when State is unchanged; the `groups` array changes reference only when the group list changes; closed group objects are never replaced. +- Forward-only folding: do not read neighboring Contexts, nodes, or later history. + +Turn-data publication: `buildLocationData` returns a value only for the turn phase and reuses its previous value when the `groups` reference is unchanged, preventing republication. A history window without `turn/start` uses the same fallback as `turn-process`: fold State from the available matches. + +Publication timing: batch live chunks at animation frames; publish other changes immediately. + +### Membership rules + +The builder assigns membership by step, not by seq ranges, because live-chunk seqs and persisted-event seqs use different scales. + +| Node | Rule | +|---|---| +| `tool-call` at step s | Belongs to the last group with `headStep ≤ s`. If text closes the preceding group in the same step, later tool calls open a new group at that step, so the last group is the applicable one | +| `assistant-step` at step s where a group has `closeStep === s` | Closer role: the node remains visible; folding the group hides only its reasoning through the existing `reasoningHidden` mechanism | +| Other `assistant-step` at step s | Member role: belongs to the group with `headStep ≤ s` whose `closeStep` has not been passed | +| `model-retry`, `turn-error`, `turn-max-tokens`, `turn-tail`, `user`, `steering` | Belong to no group | + +Recompute membership only when the group list changes, with cost proportional to that Turn's node count. Streaming chunks that leave the group list unchanged do not publish member presentation. + +The header anchors before the earliest member. If a group contains only its closer's reasoning and no members, such as reasoning followed by a reply in one step, anchor the header before the closer so the hidden reasoning still has a control that reveals it. + +### Delivering group changes to the builder + +The fold publishes Turn data, not view nodes. When Location data changes, the engine's `flush` sets `timelineDirty` and calls `apply` on all active targets, but the builder cannot identify the changed Turn and key. Inferring them from an unrelated node update in the same Turn and flush is not a reliable guarantee. + +Add optional `changedLocationData` to `ConversationViewBuilder.apply`: the Location values whose references changed in this flush, each carrying `kind`, `turn`, optional `step`, and `key`. The assembler already compares references in `applyDirtyLocationData`; it collects those results for the builder. Chat reprojects only Turns with `key === 'step-groups'`. When the optional input is absent, the builder falls back to Turns affected by the current upserts. + +### Combining hidden state in a seat + +Seats stop receiving `compactTranscript` and `historyIncomplete`. A seat reads policy through `usePresentation`, selecting its own result rather than the mode: + +```ts +declare function usePresentation(select: (policy: { + stepGrouping: 'collapsed' | 'none' + foldCompletedTurns: boolean +}) => T): T +declare const group: { readonly headStep: number } | undefined + +const grouping = usePresentation(p => group === undefined ? 'none' : p.stepGrouping) +const foldCompleted = usePresentation(p => p.foldCompletedTurns) +``` + +For a seat outside every group, `grouping` is `'none'` in all modes, so it does not re-render. `foldCompletedTurns` likewise stays true in all modes. The selector hook uses `useSyncExternalStoreWithSelector` and re-renders only when the selected value changes. + +Three sources combine into `hidden`: + +| Source | Condition | Reveal action | +|---|---|---| +| Whole-Turn folding | Existing rule: `turnClosed && turnStarted && has reply`, without manual expansion | Open the Turn | +| Group folding | `grouping === 'collapsed'`, member role, group not manually expanded | Open the group | +| Group header in Expanded | Header role and `grouping === 'none'` | None | + +The closer's reasoning is hidden independently: the seat passes `stepGroup.reasoningHidden` through owner props to the assistant-step renderer. + +The chat store keeps group expansion under a key combining `turn` and `headStep`, alongside whole-Turn manual expansion. + +### Re-render scope + +The following guarantees also define the next round of render-count assertions. Each row names an exact set, not an upper bound. + +| External change | May re-render | +|---|---| +| A running group receives a reasoning chunk | That assistant seat | +| A running group receives `tool/call` | That tool seat and the group's header | +| A reply appears and closes a group | That assistant seat and group header; membership recomputation occurs only when opening or closing groups | +| A new group opens | Insert the new header into `order` with one structural layout; no other seat refreshes | +| Switch Compact ↔ Detailed | Only assistant-step renderers with settled reasoning | +| Switch to or from Expanded | Only member and header seats | +| Change `performanceUsage` | Only turn-tail | +| Load an earlier page | New seats and historical seats whose presentation changes | +| Change locale | All seats, as a control case | + +### Presentation policy object + +Separate the persisted enum from runtime capabilities. `TranscriptViewMode` contains `compact`, `detailed`, and `expanded`; reading the legacy saved value `normal` maps it to `detailed` without writing it back. Runtime capabilities are the derived `ChatPresentationPolicy`: + +| Field | compact | detailed | expanded | +|---|---|---|---| +| `foldCompletedTurns` | true | true | true | +| `stepGrouping` | collapsed | collapsed | none | +| `settledReasoningPreview` | false | true | true | + +The mapping has one owner. Each mode maps to a constant object with a stable reference, so the derived observable needs no subscription bookkeeping: `getSnapshot` performs a lookup and `subscribe` forwards to the mode observable. + +Renderers select needed fields instead of comparing enum values. Policy is injected by kind: the assistant-step registration receives it through `inject.hooks.presentation`, just as turn-tail receives `performanceUsage`. Adding a fourth mode changes the table, not the renderers. + +### Per-Turn folding + +Add `turnStarted` to per-key presentation, derived from whether the Turn's `turn/start` is in the loaded window. Folding eligibility uses it instead of global `!historyIncomplete`. Completing pagination changes no global seat prop; only new nodes and presentation in their Turns change. + +### Complexity requirements + +| Scenario | Fold | Builder | Publication | +|---|---|---|---| +| Content chunk without a group-boundary change | O(1) transition, original object returned | No reprojection | None | +| Event that changes a group boundary | O(1) | Reproject only the owning Turn, proportional to its node count | Keys whose facts changed in that Turn | +| Structural changes and pagination | Proportional to matched events | One full pass | Keys whose facts changed | +| Mode change | None | None | None; seat and renderer selectors determine re-renders | + +## Change inventory + +| Package | File | Change | +|---|---|---| +| ui-conversation | `contract/conversation.ts` | Add `ConversationLocationDataUpdate` and optional `changedLocationData` to `ConversationViewBuilder.apply` | +| ui-conversation | `conversation/assembler.ts` | Collect changed Location references in `applyDirtyLocationData` and pass them through `apply` | +| ui-conversation | `index.ts` | Export the new type | +| ui-chat | `chat-settings.ts` | Three-mode enum; schema accepts legacy `normal` | +| ui-chat | `transcript-view.ts` | Map `normal` to `detailed` on read | +| ui-chat | New `presentation-policy.ts` | Policy objects, mapping table, derived observable | +| ui-chat | `settings/TranscriptViewRow.tsx` | Three options | +| ui-chat | `locale.ts` | Mode labels and group-header copy | +| ui-chat | `contract/slots.ts` | `ChatViewInjected.hooks.presentation`, `PresentationInjected`, `ChatNodeOwnerProps.stepGroup`, `StepGroupOwnerProps` | +| ui-chat | `contract/snapshot.ts` | `ChatTurnProcessPresentation.turnStarted`, `ChatNodeGroupPresentation`; combine `processSource` values per key | +| ui-chat | `contract/chat-nodes.ts` | `StepGroupChatData` | +| ui-chat | `contract/store.ts`, `stores.ts` | Manual group-expansion state and actions | +| ui-chat | `conversation-nodes/common.ts` | Header anchor offset | +| ui-chat | New `conversation-nodes/step-groups.ts` | Fold Definition and Turn-data declaration merging | +| ui-chat | New `conversation-nodes/step-group-nodes.ts` | Materialize headers and project membership | +| ui-chat | `conversation-nodes/turn-process-presentation.ts` | `turnStarted` and combined per-key presentation | +| ui-chat | `conversation-nodes/chat-snapshot-builder.ts` | Integrate materialization, consume `changedLocationData`, support key deletion in the store | +| ui-chat | `conversation-nodes/register.ts` | Register the fold Definition | +| ui-chat | `chat/ChatView.tsx` | Stop passing `compactTranscript` and `historyIncomplete`; pass `usePresentation` | +| ui-chat | `chat/ChatNodeSeat.tsx` | Combined selector, three hiding sources, `stepGroup` owner props | +| ui-chat | `chat/AssistantNodeView.tsx`, `chat/AssistantMarkdown.tsx`, `chat/ReasoningRow.tsx` | Inject policy, toggle settled reasoning previews, hide closer reasoning | +| ui-chat | New `chat/StepGroupNodeView.tsx` | Header renderer | +| ui-chat | `chat/register-node-renderers.ts` | Register header renderer and inject policy into assistant-step | +| ui-chat | `apply.ts`, `index.ts` | Create and inject policy observable; export types | + +This inventory retains the complete grouping proposal. Independent features have updated READMEs, i18n pairing files, and the slot catalog. The migration record tracks tests and snapshots; those updates do not complete the outstanding grouping work. + +## Acceptance criteria + +Grouping validation remains unimplemented; the migration record tracks independent presentation-feature evidence. + +**Render-count isolation.** Add counters to the existing `chat-view.client.spec` mounting approach: React Profiler `onRender` counts per seat, and test renderers registered in `conversation.chat.node` count by kind. Assert the exact sets in the re-render-scope table for each stimulus. + +**Publication counts.** Count notifications from each key's source under the same stimuli and assert the exact set. + +**Fold state-machine tests.** Feed event sequences and assert opening, closing, a new group after text then tools in one step, Turn-end closure, idempotence, unchanged closed-group references, and equivalent replay using only persisted messages. + +**Membership tests.** Given the group list and Turn nodes, assert each key's role. + +**Benchmark coverage.** Add incremental apply with reasoning and tools to `conversation-fold`, and a streaming fixture with tools and reasoning to `long-session-browser`. These provide wall-clock evidence, not a gate. + +## Risks + +- **Builder-owned node creation.** This is the first proposed node creation by a view builder. A builder may only materialize rows from Turn or Step data; it must not read events or derive business structure. Synthetic keys use `step-group:`, while Context keys begin with digits, preventing collisions. Fall back to approach A if this ownership is rejected in practice. +- **Header anchor moves once with its first member.** Persisting a streaming Assistant moves its anchor from the first visible chunk to the message event. The header follows in the Assistant's structural update. +- **Actual mode differences in this phase.** Compact and Detailed currently differ only in settled reasoning first-line previews. Running detail titles and category summaries are outside this phase; the policy table leaves room for them. +- **Pagination and partial Turns.** The oldest partial Turn neither folds nor groups. Membership uses steps and is independent of pagination. +- **Header copy.** This phase proposes only processing/completed labels and tool-call counts; category summaries remain product work. +- **Streaming chunk step.** `assistant/live-chunk` carries `step`, as used by `turn-process`; a chunk without a step does not open a group. + +## Retained alternative: parent-derived child Contexts + +If builder materialization exposes more ownership problems than expected, add an engine primitive: a Context's `update` may derive a child Context with an explicit kind and id, then forward later matches. Each child owns its node, publication timing, and Location. Parent replay aligns children by id; children no longer derived become hidden under the existing withdrawal rules. + +This returns row identity and content to Definitions with one Context per group and no array fragmentation. It requires assembler forwarding and cascaded replay, and introduces a Context creation path outside `match`. Reconsider it if more than two business features exceed the builder's materialization limits, or if membership requires cases that steps cannot express. diff --git a/.agents/notes/proposed/architecture/2026-09-20-chat-presentation-policy-and-step-groups.zh.md b/.agents/notes/proposed/architecture/2026-09-20-chat-presentation-policy-and-step-groups.zh.md index 88ee6a4986..1bf9cf9517 100644 --- a/.agents/notes/proposed/architecture/2026-09-20-chat-presentation-policy-and-step-groups.zh.md +++ b/.agents/notes/proposed/architecture/2026-09-20-chat-presentation-policy-and-step-groups.zh.md @@ -2,9 +2,11 @@ Status: proposed +[English](2026-09-20-chat-presentation-policy-and-step-groups.md) | 中文 + ## 问题 -Chat 的「对话显示」设置今天只有两档:`normal` 不折叠、`compact` 在轮次结束后把过程行折进一个整轮控件。设置值的流向是:`TranscriptViewPolicy.mode` 观察量注入 ChatView,ChatView 用 `useTranscriptView` 读成一个布尔值 `compactTranscript`,再作为 prop 传给 `ChatNodeList`,再传给每一个 `ChatNodeSeat`。另一个全局布尔值 `hasMore` 走同一条路,以 `historyIncomplete` 的名字进每个 seat。两个值一变,全部 seat 重渲染一遍,哪怕只有可折叠的那几个输出真的变了。 +Chat 的「对话显示」设置在本提案开始时只有两档:`normal` 不折叠、`compact` 在轮次结束后把过程行折进一个整轮控件。设置值的流向是:`TranscriptViewPolicy.mode` 观察量注入 ChatView,ChatView 用 `useTranscriptView` 读成一个布尔值 `compactTranscript`,再作为 prop 传给 `ChatNodeList`,再传给每一个 `ChatNodeSeat`。另一个全局布尔值 `hasMore` 走同一条路,以 `historyIncomplete` 的名字进每个 seat。两个值一变,全部 seat 重渲染一遍,哪怕只有可折叠的那几个输出真的变了。 产品要把这个设置改成三档:简洁、详细、完全展开;并在简洁和详细两档里把回复之间的连续过程行归成可折叠的组。PR #4565 做过一次完整实现,合并八分钟后因性能回退被整体撤回。合并前后在本机的对照实测:长会话分页耗时 +27%,DOM 节点 +23%,堆内存 +14%,Trajectory 切换 +10%,全部仍在 CI 预算内;仓库现有六个基准没有任何一个覆盖「流式期间 reasoning 或工具 chunk 进入活动分组、分组重投影、seat 重渲染」这条它新增的热路径。 @@ -19,6 +21,8 @@ Chat 的「对话显示」设置今天只有两档:`normal` 不折叠、`compa 本记录给出一套基础架构,让三档模式与分组落地时满足下面的约束,并让后续产品变化只落在少数节点上。 +三档设置、展示策略通道与按轮折叠资格已实现;step-group 仍是提案。当前实现、已提交范围和未完成项以[迁移进度表](../feature/2026-09-20-chat-work-details-migration.zh.md)为准,下面的分组状态机与改动清单不表示已经交付。 + ## 目标与约束 下表是评审阶段已经确认的裁决,本方案不再重新讨论它们。 @@ -31,7 +35,7 @@ Chat 的「对话显示」设置今天只有两档:`normal` 不折叠、`compa | 4 | 模式不开关 Definition | 注册变化会触发 registry 重建与全量重放,所有 seat 必刷;Definition 必须与模式无关 | | 5 | 折叠按轮判定 | 一轮只要自己的 `turn/start` 已加载就可以折叠;被分页切开的最老一轮保持展开,本轮不优化 | | 6 | 允许改 ui-conversation | 引擎可以改,但只做让方案正确成立所必需的小改动 | -| 7 | 本轮范围 | 只写代码与本记录;不写测试,不改其他文档;测试与文档在下一轮补 | +| 7 | 初始实现范围 | 初始阶段只写代码与本记录;测试与其他文档在 CI 修复阶段补齐 | 有一条前置澄清:接受「切模式全屏重排版」不等于接受「所有 seat 重渲染」。浏览器重排是几何结果,seat 重渲染是 React 组件函数重跑,后者才是这里要限制的量。 @@ -49,7 +53,7 @@ Chat 的「对话显示」设置今天只有两档:`normal` 不折叠、`compa **路线 δ,Definition 拥有结构,builder 物化行。** turn 级 Definition 折叠出组列表并发布为 Turn 数据;Chat builder 据此物化组头节点并给成员写归属;seat 用组合 selector 决定隐藏;引擎给 `ViewBuilder.apply` 的入参加一份「本次 flush 哪些 Location 数据换了引用」。 -## 砍掉的路线与理由 +## 备选方案与取舍 **每组一个 Context 无法成立。** 引擎要求 `match(event)` 只看单个事件算出 id,「第几组」取决于前面有没有回复,单个事件算不出。这不是实现难度,是契约上的不可能。 @@ -154,6 +158,12 @@ fold 只发布 Turn 数据,没有视图节点。engine 的 `flush` 在 Locatio seat 不再接收 `compactTranscript` 与 `historyIncomplete` 两个 prop。它通过 `usePresentation` 读策略,但选出的不是模式,而是自己的结论: ```ts +declare function usePresentation(select: (policy: { + stepGrouping: 'collapsed' | 'none' + foldCompletedTurns: boolean +}) => T): T +declare const group: { readonly headStep: number } | undefined + const grouping = usePresentation(p => group === undefined ? 'none' : p.stepGrouping) const foldCompleted = usePresentation(p => p.foldCompletedTurns) ``` @@ -244,11 +254,11 @@ per-key presentation 增加 `turnStarted`,来源是该轮 `turn/start` 是否 | ui-chat | `chat/register-node-renderers.ts` | 注册组头渲染器;给 assistant-step 注入策略 | | ui-chat | `apply.ts`、`index.ts` | 创建策略观察量并注入;导出类型 | -本轮不改:README、i18n 配对文件、slot catalog、测试、快照。slot catalog 中 `ChatNodeOwnerProps` 的源码摘录与 key 列表需要在提 PR 前重新生成。 +上述清单保留完整分组方案;独立功能已经更新 README、i18n 配对文件及 slot catalog。测试与快照进度见迁移记录,未完成的分组改动不随这些更新自动完成。 ## 验收标准 -下一轮补齐,本轮不实现。 +分组相关验收仍待实现;独立展示功能的验证进度见迁移记录。 **渲染次数隔离测试。** 在现有 `chat-view.client.spec` 的挂载方式上加计数:React Profiler 的 `onRender` 按 seat 计数,测试专用的计数渲染器注册进 `conversation.chat.node` 按 kind 计数。刺激与期望按「刷新范围」一节的表逐行断言精确集合。 @@ -260,7 +270,7 @@ per-key presentation 增加 `turnStarted`,来源是该轮 `turn/start` 是否 **基准补位。** `conversation-fold` 增加带推理与工具的增量 apply 场景;`long-session-browser` 增加带工具与推理的流式 fixture。这是墙钟兜底,不是门禁。 -## 风险与待决 +## 风险 - **builder 产出节点的边界。** 这是这套架构里第一次由视图 builder 产出节点。边界写死为:builder 只能从 Turn 或 Step 数据物化行,不能读事件,不能自己算业务结构。合成 key 用 `step-group:` 前缀,Context key 以数字开头,不会冲突。如果实践中被否决,退到路线 A。 - **组头锚点随头成员移动一次。** 头成员是流式 Assistant 时,落盘让锚点从首个可见 chunk 移到消息事件,组头跟着移动一次。与 Assistant 自己的结构性更新同时发生。 diff --git a/.agents/notes/proposed/feature/2026-09-20-chat-work-details-migration.i18n.yaml b/.agents/notes/proposed/feature/2026-09-20-chat-work-details-migration.i18n.yaml new file mode 100644 index 0000000000..1f41262d74 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-09-20-chat-work-details-migration.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/proposed/feature/2026-09-20-chat-work-details-migration.md +2026-09-20-chat-work-details-migration.md: cd5dbe723425d5bed719bbb579305e3f917d0cc5 +2026-09-20-chat-work-details-migration.zh.md: 4055b027fc7e5c710358886361badb88a4e9b13e diff --git a/.agents/notes/proposed/feature/2026-09-20-chat-work-details-migration.md b/.agents/notes/proposed/feature/2026-09-20-chat-work-details-migration.md new file mode 100644 index 0000000000..cd5dbe7234 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-09-20-chat-work-details-migration.md @@ -0,0 +1,144 @@ +# Agent Note: Chat work-details migration progress + +Status: proposed + +English | [中文](2026-09-20-chat-work-details-migration.zh.md) + +## Problem + +PR #4565 combines three display modes, process grouping, whole-Turn status, trigger notifications, tool-row visuals, and infrastructure-row hiding. Migrating it as one batch mixes independent features with list restructuring and makes individual performance changes difficult to assess. A feature-based progress table allows independent visuals to be reviewed first and Turn-related behavior to be considered with step-group later, without losing product requirements. + +## Proposal + +Completed independent features stay in `feat/chat-presentation-channel`. The remaining unfinished code continues in `.artifacts/worktrees/pr-4565-turnstep` under the repository root, based on the current channel and this progress record, with drafts kept unstaged for combined turn/step and grouping review. The `pr-4565` worktree remains the original PR's behavior and implementation reference; existing `feat/chat-step-groups` experiments are outside this transfer. + +This record tracks feature scope, current implementation, and acceptance progress. The [presentation policy channel and process-group architecture](../architecture/2026-09-20-chat-presentation-policy-and-step-groups.md) retains the architecture and alternatives. This record neither replaces it nor treats its proposals as implemented. Because it does not fully supersede that decision, retain the architecture note without archival or deletion. + +This record maintains an English/Chinese pair. Completion, implementation, staging or commit state, and acceptance are separate dimensions. Incomplete items remain marked incomplete even when drafts exist, and stay in the inventory. Tests and documentation are added during CI repair; browser snapshots and performance acceptance are tracked separately. Written code, staging, commits, and successful builds do not establish complete functional or performance acceptance. + +### Status definitions + +| Dimension | State | Meaning | +|---|---|---| +| Completion | Complete | Migration code has been reviewed feature by feature and committed to this channel; behavior and performance evidence are separate | +| Completion | Incomplete | Outside the channel's completed migration scope; may have an unstaged draft or no implementation | +| Implementation | Existing capability | Already present in this channel | +| Implementation | Code written | Implementation exists in the relevant worktree; does not imply completion, staging, commit, or acceptance | +| Implementation | Awaiting migration | Included in non-grouping scope but not yet implemented | +| Implementation | Grouping phase | Requirement retained; depends on grouping structure or interactions and is not connected to this channel yet | +| Staging or commit | Unstaged | Changes remain in the worktree, including untracked files | +| Staging or commit | Partially staged | Only some feature changes are staged; the exact scope must be stated | +| Staging or commit | Staged | All pending code changes for the feature are staged but not committed | +| Staging or commit | Committed | Feature code is included in current HEAD | +| Acceptance | Pending | Requires behavior, node identity, update-scope, or browser performance evidence; Git state and compilation cannot substitute | + +Verify staging against the feature's diff hunks, not whole files. Inspect the worktree, index, and HEAD when updating status. Staging some fields in a shared file does not stage every feature depending on that file. + +### Capabilities already in this channel + +| Capability | compact | detailed | expanded | Completion | Implementation | Staging or commit | Acceptance | +|---|---|---|---|---|---|---|---| +| Three settings and legacy-value reading | Compact | Detailed; legacy `normal` reads as this mode without write-back | Expanded | Complete | Existing capability | Committed | Pending | +| Per-Turn folding eligibility | A closed Turn with its start loaded and a final reply can fold process content; cancellation/failure extensions are item 6 | Same | Same | Complete | Existing capability | Committed | Pending | +| Collapsed settled-reasoning summary | Think title only | First line | First line | Complete | Existing capability | Committed | Pending | +| Retain summary DOM across mode changes | CSS hides summary and separator | Show existing summary and separator | Same | Complete | Existing capability | Committed | Pending | +| Local reasoning-preview subscription | `ReasoningRow` selects its own visibility | Same | Same | Complete | Existing capability | Committed | Pending | +| Stable disclosure-row references | Callbacks, icons, and unchanged summaries retain references; full Markdown mounts only on expansion | Same | Same | Complete | Existing capability | Committed | Pending | + +All three modes retain whole-Turn folding. `expanded` means removing secondary process groups, not disabling whole-Turn folding or automatically expanding reasoning and tool-card bodies. Until grouping is connected, Chat presents `detailed` and `expanded` identically. + +### Migration inventory without grouping dependencies + +“All three modes” means the behavior applies in every mode, not that switching modes changes it. “Without grouping dependencies” means the draft introduces no step-group, not that every item must be accepted before grouping. Numbers follow the feature review inventory; item 0's compilation wiring is complete and committed, so it is not listed as a product feature. Incomplete drafts remain in `pr-4565-turnstep`, outside this channel's completed features. Behavior and performance acceptance remain pending for the features below. + +| Number | Feature | compact | detailed | expanded | Completion | Implementation | Staging or commit | Destination and considerations | +|---|---|---|---|---|---|---|---|---| +| 1 | Chinese tool titles | All three modes | All three modes | All three modes | Complete | Code written | Committed | Bash/Pwsh: “运行命令”; Grep: “搜索文件内容”; Glob: “查找文件”; Skill: “加载技能”. Only UI dictionaries change; model tool names do not | +| 2 | Tool-row interaction visuals | All three modes | All three modes | All three modes | Complete | Code written | Committed | Hover darkens titles and summaries in tool, Bash, and command rows; shared `DisclosureRow` and independent Bash rows point the expanded chevron upward | +| 3 | Bash stopped-state screen-reader text | All three modes | All three modes | All three modes | Complete | Code written | Committed | Complete the stopped-state accessible name without changing execution or cancellation semantics | +| 4 | Running tool/command text shimmer | All three modes | All three modes | All three modes | Complete | Code written | Both 4A shimmer and 4B accompanying optimizations committed | 4A includes a fixed `TextShimmer` span, CSS activation, tool/command integration, replacement of old sweep styles, and reduced-motion support, excluding step/turn. 4B adds business-row computation caches, stable callbacks, and JSX references | +| 5 | Streaming reasoning summary | Update after a paragraph's first line completes | Same | Same | Complete | Code written | Committed | `ReasoningRow` retains the original PR's `latestCompletedParagraphFirstLine(text)` and computes from full text. Retain summary DOM, stable props, and right-edge fading; add no Definition parsing state or cross-layer summary fields | +| 6 | Keep process expanded after cancellation/failure | All three modes | All three modes | All three modes | Incomplete | Draft code written | Unstaged | Draft uses `keepOpen` in Turn process projection; folding eligibility and stopped/failed behavior await Turn/grouping review | +| 7 | Whole-Turn status and duration control | All three modes | All three modes | All three modes | Incomplete | Draft code written | Unstaged | Draft anchors the control to loaded `turn/start` after opening inputs, isolates timing in `LiveTurnProcessLabel`, and replaces the bottom activity bar; positioning and status await review | +| 8 | Non-human trigger notifications | All three modes | All three modes | All three modes | Incomplete | Draft code written | Unstaged | Draft identifies waking inputs from next-turn and first-step next-step claims and projects `turn-trigger`; Turn starts, notification ownership, and expanded content await review | +| 9 (permission/system) | Hide permission-command and system-prompt rows | All three modes | All three modes | All three modes | Complete | Code written | Committed | `isVisibleChatNode` centralizes filtering for the existing Chat list, navigation, and process presentation. Command and request-prompt Definitions do not own these filters; persistence and Trajectory are unchanged | +| 9 (context) | Hide ordinary Context rows | All three modes | All three modes | All three modes | Incomplete | Draft code written | Unstaged | Paired with item 8's waking notifications to retain source explanations; final filter ownership awaits Turn/grouping review | +| 10 | Turn action-bar positioning | All three modes | All three modes | All three modes | Incomplete | Draft code written | Unstaged | Draft anchors `turn-tail` after `turn/end`; reply ownership for feedback/copy and the real Turn-end seq for branching await combined review | +| 11 | Action-bar persistent visibility | All three modes | All three modes | All three modes | Incomplete | Draft code written | Unstaged | Draft projects `footer` per Turn in the Chat builder: persistently visible when the latest Turn ends in a reply, otherwise on hover/focus; tail detection will be considered with grouping | + +The current base already enables developer tools by default; do not migrate that again. Retain the protection that waits for Host acceptance of settings instead of applying the original PR's missing-value fallback. Its `Switch` change only affects a comment and is not a migrated feature. + +### Subsequent review batches + +Review batches are independent of implementation and staging status. Review remaining drafts in `pr-4565-turnstep`, kept unstaged; a draft does not complete a migration. Transfer only this channel's remaining code, without automatically incorporating `feat/chat-step-groups` experiments or installing dependencies and compiling in the destination worktree. + +| Batch | Features | Review scope | +|---|---|---| +| Independent feature, committed | 4A: text shimmer | `TextShimmer`, row integration, and browser painting cost; performance acceptance pending | +| Independent optimization, committed | 4B: accompanying memoization and reference stability | `ToolRow`, `BashRow`, and `GenericCommandCard` computation caches, callbacks, and JSX references; not required for shimmer itself; performance acceptance pending | +| Independent feature, committed | Permission-command and system-prompt hiding from item 9 | Retain the original PR's centralized visibility decision; without step-group, the main list connects it in `orderedVisibleChatNodes`, independent of waking-message classification | +| Incomplete, transferred to turnstep worktree | 6, 7, 10, 11 | Whole-Turn folding eligibility, status/clock, action-bar position, and tail detection, considered with Turn/group relationships | +| Incomplete, transferred to turnstep worktree | 8 and ordinary Context hiding from item 9 | Trigger notifications depend on Turn starts and Inbox claims; Context hiding accompanies notifications so waking reasons remain visible | + +### Requirements retained for the grouping phase + +All items below remain incomplete and retain their full requirements for the turn/step and grouping phase. Neither this channel nor the transferred drafts introduce step-group. Experimental code in `feat/chat-step-groups` does not establish completion of these product behaviors or performance requirements. + +| Feature | compact | detailed | expanded | Current state | +|---|---|---|---|---| +| Consecutive process groups between replies | Group tools and reasoning, initially collapsed | Same | Show process rows directly without secondary wrappers | Incomplete (grouping phase) | +| Independent reasoning/reply visibility within one Assistant | Reasoning may join the preceding group; reply stays visible | Same | No secondary group hiding | Incomplete; do not directly copy the original split into two render nodes | +| Header category summary | Current category while running; aggregate main categories after completion | Same | No header | Incomplete (grouping phase) | +| Running header details | Hidden | Show command, path, query, etc.; reasoning summary when no tool is running | No header | Incomplete (grouping phase) | +| Header update cadence | Preserve category title's minimum display duration | Also handle detail updates | Not applicable | Incomplete (grouping phase) | +| Height-limited scrolling within a group | Limit expanded height, scroll independently, fade edges | Same | Not applicable | Incomplete (grouping phase) | +| Group and whole-Turn folding interaction | Hide groups when the Turn folds | Same | Whole-Turn folding only | Incomplete; retain node identity and separately decide whether internal expansion resets | +| Pagination, streaming settlement, and group identity | Stable existing headers and members; handle partial Turns separately | Same | Show the same business nodes directly | Incomplete (grouping phase) | + +Grouping details to verify: completed summaries aggregate at most three categories and use “etc.” beyond three; call counts determine category ordering rather than appearing as header numbers. Detailed-mode live details collapse whitespace and are capped at 160 characters. Titles remain for at least 150ms; retain only the latest update without replaying queued updates. Expanded height is at most the smaller of 400px and half the viewport. Scrollable edges use a 24px fade and preserve interaction with outer scrolling. Retry rows are outside secondary groups. These values describe the original PR's reference behavior, not completed grouping experiments. + +## Performance constraints + +| Scenario | Property to preserve | Required evidence | +|---|---|---| +| Switching among modes | Business-node keys do not change; modes do not re-register Definitions; only relevant visibility/presentation fields update | Node identity and update-scope checks | +| Incremental reasoning/tool content | Update only the owning node without scanning full history; compute reasoning summary from current full text during rendering | Update scope and long-text cost; the current summary algorithm does not reduce `ReasoningRow` render count | +| Whole-Turn running clock | Only live clock content updates each second, without refreshing members, historical rows, or list | Update scope and timer disposal | +| Summary visibility | Keep lightweight summaries mounted; do not mount every full Markdown body for mode switching | DOM identity, initial loading, memory observations | +| Pagination | Update new nodes and nodes with changed facts; completed Turns do not refresh together because of global pagination state | Multi-page interaction and update-scope checks | +| State transitions | Stable text/icon/callback references when content is unchanged; do not clear internal state through remounting | Interaction state and component lifecycle checks | + +Retaining DOM reduces mounting and unmounting cost, not style calculation, layout, or painting, and can increase retained memory. Changing display properties alone is not a guarantee against jank. The aim is lower switching peaks with acceptable initial-load, pagination, and streaming costs. + +## Alternatives considered + +**Replay the original PR as one batch.** Rejected: grouping, node splitting, whole-Turn status, and independent visuals would mix, obscuring each feature's performance effects and overwriting local subscriptions and node reuse already completed in this channel. + +**Unmount and recreate summaries or process nodes on mode changes.** Rejected for summary mode changes. Stable mounts allow repeated switching to change only display state; initial costs for new nodes still require separate validation. + +**Keep every Markdown body mounted for smooth switching.** Rejected: lightweight summaries and full bodies differ in memory, DOM, and rendering cost. Bodies remain mounted according to manual expansion. + +**Remount renderers when folding a Turn to reset tool cards.** Do not migrate directly. It conflicts with stable nodes and preserved interaction state. If reset behavior remains necessary, define its state owner and trigger explicitly. + +## Acceptance criteria + +Update implementation, staging, and commit status separately as work progresses. Completion follows feature review and commits; acceptance follows actual validation. Retain incomplete items across branch splits and worktree transfers. Before grouping work starts, check every product requirement and mode mapping above. + +| Acceptance item | Current state | +|---|---| +| Complete behavior validation of existing channel capabilities | Relevant unit and browser regressions pass; this excludes unmigrated grouping features and does not establish performance acceptance | +| Non-grouping feature migration | Completed scope is in the inventory; incomplete drafts await review in `pr-4565-turnstep`; functional and performance validation remain incomplete | +| DOM identity and update scope during mode changes | Unit tests verify summary/expanded-body DOM identity and policy-field subscriptions; browsers verify persistence of all modes and whole-Turn folding; whole-page update scope and performance remain pending | +| Long-session initial loading, pagination, streaming, and memory | Pending; the original PR's historical measurements do not validate this implementation | +| Unit, browser, and recorded-snapshot coverage | 785 relevant unit tests pass; read-only replay of 35 browser files yields 178 passing tests and 4 conditional skips; UI expectations are updated and Session JSONL is unchanged | +| Grouping and the Detailed/Expanded distinction | Incomplete (grouping phase) | + +Validation evidence: after rebasing onto master, this channel passed full `pnpm run build`, lint, duplication checks, and all 41 documentation checks. New presentation policy, shimmer, and visibility filtering, plus the settings and Skill rows reported by CI, pass 100% coverage checks over their selected source scope. Test repairs, UI snapshots, and bilingual pairing are committed together as CI fixes. No install, build, or tests ran in `pr-4565-turnstep`; this channel's results do not establish acceptance for that worktree. A real-model GUI demo and performance measurements remain outstanding. + +## Risks + +- `expanded` and `detailed` currently present identically; the original PR's distinction exists only after grouping is implemented. +- Whole-Turn duration replaces the existing tool/message-count title, changing product information. Migration must preserve status, accessible names, and Turns with no process content, not merely restyle the control. +- Hiding ordinary Context before adding trigger notifications removes background waking reasons; connect both items in the inventory's order. +- The original footer decision depends on grouping indexes. Rework ownership per feature rather than introducing the whole grouping infrastructure for a footer. +- Group identity, membership, and builder materialization in the experiments still require evaluation; this record does not treat the experiment as final architecture. diff --git a/.agents/notes/proposed/feature/2026-09-20-chat-work-details-migration.zh.md b/.agents/notes/proposed/feature/2026-09-20-chat-work-details-migration.zh.md index 964d37d9d3..4055b027fc 100644 --- a/.agents/notes/proposed/feature/2026-09-20-chat-work-details-migration.zh.md +++ b/.agents/notes/proposed/feature/2026-09-20-chat-work-details-migration.zh.md @@ -2,6 +2,8 @@ Status: proposed +[English](2026-09-20-chat-work-details-migration.md) | 中文 + ## 问题 PR #4565 同时包含三档展示设置、过程分组、整轮状态、触发通知、工具行视觉和基础设施行隐藏。整批迁移会把独立功能与列表重组混在一起,也难以逐项判断性能变化。需要一份按功能维护的进度表,先评审独立视觉功能,再结合 step-group 统一考虑轮次相关行为,避免遗漏原有产品需求。 @@ -12,7 +14,7 @@ PR #4565 同时包含三档展示设置、过程分组、整轮状态、触发 本记录管理功能范围、当前实现和验收进度。[展示策略通道与过程分组的基础架构](../architecture/2026-09-20-chat-presentation-policy-and-step-groups.zh.md)保留架构路线及备选方案;本记录不替代它,也不把其中的方案视为已经实现。新记录没有完整取代既有架构决策,因此保留原记录,不做归档或删除。 -本记录处于开发阶段,只维护中文版。完成状态、实现状态、暂存或提交状态、验收状态分别记录。未完成项即使已有代码草稿,也继续标为未完成,不从清单移除。测试断言、README 和录制快照留待后续;代码写好、进入暂存区、提交或构建通过,都不等同于功能或性能验收。 +本记录维护中英文配对。完成状态、实现状态、暂存或提交状态、验收状态分别记录。未完成项即使已有代码草稿,也继续标为未完成,不从清单移除。测试和文档随 CI 修复补齐,浏览器快照与性能验收单独记录;代码写好、进入暂存区、提交或构建通过,都不等同于完整功能或性能验收。 ### 状态定义 @@ -124,14 +126,14 @@ PR #4565 同时包含三档展示设置、过程分组、整轮状态、触发 | 验收项 | 当前状态 | |---|---| -| 当前通道已有能力的完整行为验证 | 待验收;既有测试包含只做类型接线、尚未调整的旧断言 | +| 当前通道已有能力的完整行为验证 | 已通过本次相关单元和浏览器回归;不包含未迁移的分组功能,也不代表性能验收 | | 非分组功能迁移 | 完成范围见迁移清单;未完成草稿留到 `pr-4565-turnstep` 继续评审,功能与性能验证仍未完成 | -| 模式切换时的 DOM 身份和刷新范围 | 待验收;不能以 memo 或 selector 的存在代替实际证据 | +| 模式切换时的 DOM 身份和刷新范围 | 单元测试已验证摘要、手动展开正文的 DOM 身份和策略字段订阅;浏览器已验证三档持久化及整轮折叠,整页刷新范围与性能仍待验收 | | 长会话首次打开、分页、流式输入与内存 | 待验收;原 PR 的历史测量不代表本实现 | -| 新行为的单元、浏览器与录制快照覆盖 | 待补;开发阶段不在此轮运行测试或录制 | +| 新行为的单元、浏览器与录制快照覆盖 | 相关单元测试 785 项通过;35 个浏览器文件只读回放,178 项通过、4 项按条件跳过;UI 预期输出已更新,Session JSONL 未改动 | | 分组功能与两档差异 | 未完成(分组阶段) | -历史构建记录:迁移草稿曾通过三个源码包的单独 TypeScript 构建和完整 `pnpm run build`。首轮构建暴露的展示策略辅助文件编译归属问题已修正并提交,没有调整测试断言。该记录不代表拆分后的当前通道或 turnstep 工作区已重新验证;本次仅提交进度记录并搬迁草稿,不安装依赖、不编译、不执行测试、快照或性能基准。 +验证记录:当前通道在 rebase master 后通过完整 `pnpm run build`、lint、重复代码检查和完整文档检查(41 项)。新增展示策略与扫光、可见性过滤,以及 CI 报告的设置行和 Skill 行覆盖率已通过对应源码范围的 100% 检查。测试修复、UI 快照和中英配对随 CI 修复一并提交;`pr-4565-turnstep` 未执行安装、构建或测试,当前通道的结果不代表该工作区已验收。真实模型 GUI 演示和性能测量仍待补。 ## 风险 diff --git a/apps/web/tests/chat-continuous-conversation.e2e.ts b/apps/web/tests/chat-continuous-conversation.e2e.ts index 810336de88..de94289607 100644 --- a/apps/web/tests/chat-continuous-conversation.e2e.ts +++ b/apps/web/tests/chat-continuous-conversation.e2e.ts @@ -340,9 +340,9 @@ describe('web e2e: continuous conversation grown through the composer', () => { ))).toHaveLength(TURN_COUNT) expect(sessionEvents.flatMap(event => event.type === 'request/header' ? [event.data.reason] : [])).toEqual(['initial']) - expect(await page.getByRole('button', { name: 'System prompt' }).count()).toBe(1) + expect(await page.getByRole('button', { name: 'System prompt' }).count()).toBe(0) expect(await page.locator( - '[data-chat-flow-kind="system-prompt"][hidden="until-found"]', + '[data-chat-flow-kind="system-prompt"]', ).count()).toBe(0) expect(specs.at(-1)?.prompt.length).toBeGreaterThan(4_000) expect(sessionEvents.flatMap(event => ( diff --git a/apps/web/tests/expected/cordis-history/ui.expected.md b/apps/web/tests/expected/cordis-history/ui.expected.md index 2ddd03bddb..1b37b0484f 100644 --- a/apps/web/tests/expected/cordis-history/ui.expected.md +++ b/apps/web/tests/expected/cordis-history/ui.expected.md @@ -9,14 +9,13 @@ - button "Jump to turn 1" - button "Jump to turn 2" - button "Jump to turn 3" -- button "System prompt" - text: "Use only Cordis tools. First call cordis_inspect_self with no arguments. Then call cordis_define with plugin kind \"new\", idPrefix \"snap\", name \"snapshot noop\", purpose \"does nothing, for the snapshot\", code.host exactly \"return { name: \\\"snapshot-noop\\\", apply(ctx) {} }\" and code.client exactly \"return { inject: [\\\"slots\\\"], apply(ctx) { ctx.slots.register({ name: \\\"shell.overlay\\\", id: \\\"snapshot-probe\\\" }, () => React.createElement(\\\"div\\\", { \\\"data-snapshot-probe\\\": \\\"loaded\\\" })) } }\". Read its returned pluginId and packageId, then call cordis_run with those exact IDs and mode \"run\". After the run request returns, reply exactly CORDIS_UI_READY and stop. 9/1 {{clock}}" - button "Copy" - button "3 tool calls" [expanded] - button "Context injection runtime-context" -- button "Think I will inspect the current Session's dynamic Cordis Plugins before defining the snapshot Package." +- button "Think" - button "Inspect plugins 0 dynamic plugins" -- button "Think No dynamic Plugins are present, so I will define the requested Host and Client Package." +- button "Think" - button "Register Cordis Plugin snapshot noop does nothing, for the snapshot Ready" [expanded] - tablist "Plugin source": - tab "Client" @@ -27,11 +26,11 @@ - code: "return { name: \"snapshot-noop\", apply(ctx) {} }" - text: Result Defined snap-1/pkg-1 (snapshot noop); it is not running yet. Use cordis_run to activate this Package. Run controls live in the Cordis panel above Settings - button "Inspect" -- button "Think The Host returned snap-1/pkg-1, so I will request its first activation." +- button "Think" - text: Run Cordis Plugin snap-1 · pkg-1 Ready - button "Inspect" - text: snap-1/pkg-1 is awaiting user approval (run-1). -- button "Think The activation request has been submitted, so I will return the requested readiness marker." +- button "Think" - paragraph: CORDIS_UI_READY - button "Copy" - button "Good response" diff --git a/apps/web/tests/expected/fork-mid-turn/ui.expected.md b/apps/web/tests/expected/fork-mid-turn/ui.expected.md index 1350afec53..6c9e8eeaa5 100644 --- a/apps/web/tests/expected/fork-mid-turn/ui.expected.md +++ b/apps/web/tests/expected/fork-mid-turn/ui.expected.md @@ -1,12 +1,10 @@ -- button "System prompt" - text: "Use the read tool twice in one assistant message: read a.txt and b.txt. Then reply with the single word DONE and stop. {{clock}}" - button "Copy" -- button "Think The user wants me to read a.txt and b.txt, then reply with \"DONE\". Let me do both reads in parallel." +- button "Think" - text: Failed - 'button "Read The history inherited by this branch records this tool call starting but does not include its result. The parent session may have completed it after the fork point. Decide whether to retry from the tool semantics: retry only if the operation is read-only or idempotent; if it may have side effects, first verify external state or ask the user. Do not retry blindly."' - text: Failed - 'button "Tool call The history inherited by this branch has no record of this tool call starting. The parent session may have executed it after the fork point. Decide whether to retry from the tool semantics: retry only if the operation is read-only or idempotent; if it may have side effects, first verify external state or ask the user. Do not retry blindly."' -- button "System prompt" - text: FORK_BRANCH_USER Summarize what this branch knows about the reads. {{clock}} - button "Copy" - button "Thought for a while" 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 4abbc3d013..6fbf824a1b 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 @@ -16,7 +16,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - button "Thought for a while" [expanded] - button "Context injection webhook github webhook handled by review-pr-when-ready" - button "Context injection runtime-context" 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 7c18886de2..1b30edc3e0 100644 --- a/apps/web/tests/expected/github-ready-review/conversation.expected.md +++ b/apps/web/tests/expected/github-ready-review/conversation.expected.md @@ -16,7 +16,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - button "Thought for a while" - paragraph: "Review complete: no actionable findings." - button "Copy" diff --git a/apps/web/tests/expected/settings-chrome/dialog-en.expected.md b/apps/web/tests/expected/settings-chrome/dialog-en.expected.md index 1337d351d5..3f945d9cce 100644 --- a/apps/web/tests/expected/settings-chrome/dialog-en.expected.md +++ b/apps/web/tests/expected/settings-chrome/dialog-en.expected.md @@ -18,7 +18,7 @@ - text: Font size Only affects conversation content 14 - button "Increase font size" - button "Decrease font size" - - text: px Conversation display Controls process content in completed turns + - text: px Work details Controls how turns and steps expand by default - button "Compact" - text: Performance & usage Choose how much performance and usage information to show - button "Detailed" diff --git a/apps/web/tests/expected/settings-chrome/dialog-no-browser.expected.md b/apps/web/tests/expected/settings-chrome/dialog-no-browser.expected.md index 1337d351d5..3f945d9cce 100644 --- a/apps/web/tests/expected/settings-chrome/dialog-no-browser.expected.md +++ b/apps/web/tests/expected/settings-chrome/dialog-no-browser.expected.md @@ -18,7 +18,7 @@ - text: Font size Only affects conversation content 14 - button "Increase font size" - button "Decrease font size" - - text: px Conversation display Controls process content in completed turns + - text: px Work details Controls how turns and steps expand by default - button "Compact" - text: Performance & usage Choose how much performance and usage information to show - button "Detailed" diff --git a/apps/web/tests/expected/settings-chrome/dialog.expected.md b/apps/web/tests/expected/settings-chrome/dialog.expected.md index 74db4241cd..c0a1b2ed35 100644 --- a/apps/web/tests/expected/settings-chrome/dialog.expected.md +++ b/apps/web/tests/expected/settings-chrome/dialog.expected.md @@ -18,8 +18,8 @@ - text: 字号大小 仅影响会话内容的字号 14 - button "增大字号" - button "减小字号" - - text: px 对话显示 控制已完成轮次的过程内容 - - button "紧凑" + - text: px 工作过程展示 控制轮次和步骤的默认展开方式 + - button "简洁" - text: 性能与用量 选择性能与用量信息展示的详细程度 - button "详细" - text: 开发者工具 显示用于调试和排查问题的工具与信息 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 1876f63c32..9540d8b21f 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 @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - button "/user-invoke-demo" - button "meeting notes.md" - text: and confirm the fixture wiring {{clock}} 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 b66832d25e..a1a363ff59 100644 --- a/apps/web/tests/expected/skill-user-invoke/ui.expected.md +++ b/apps/web/tests/expected/skill-user-invoke/ui.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - button "/user-invoke-demo" - button "meeting notes.md" - text: and confirm the fixture wiring {{clock}} 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 f3e9564660..13cc723a67 100644 --- a/apps/web/tests/expected/steer-all/mid-steer.expected.md +++ b/apps/web/tests/expected/steer-all/mid-steer.expected.md @@ -6,11 +6,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Use the ask_user_question tool to ask me exactly one question with id "checkpoint", question "Ready to continue?", header "Checkpoint", and options labeled "Yes" and "No". After I answer, reply with one short sentence acknowledging my answer and stop. {{clock}} - button "Copy" - button "Context injection runtime-context" -- button "Think The user wants me to ask them a checkpoint question first, then continue with whatever they interject. Let me do exactly that." +- button "Think" - status: Deep diving... - text: "Interjection: include the word BANANA in your final reply." - button "Copy" 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 9538b35054..0cbd3e6544 100644 --- a/apps/web/tests/expected/steer-all/settled-expanded.expected.md +++ b/apps/web/tests/expected/steer-all/settled-expanded.expected.md @@ -6,12 +6,11 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Use the ask_user_question tool to ask me exactly one question with id "checkpoint", question "Ready to continue?", header "Checkpoint", and options labeled "Yes" and "No". After I answer, reply with one short sentence acknowledging my answer and stop. {{clock}} - button "Copy" - button "1 tool call" [expanded] - button "Context injection runtime-context" -- button "Think The user wants me to ask them a checkpoint question first, then continue with whatever they interject. Let me do exactly that." +- button "Think" - button "Ask question 1/1 answered" - text: "Interjection: include the word BANANA in your final reply. {{clock}}" - button "Copy" diff --git a/apps/web/tests/expected/steer-all/settled.expected.md b/apps/web/tests/expected/steer-all/settled.expected.md index 870a712c04..92445bc6c1 100644 --- a/apps/web/tests/expected/steer-all/settled.expected.md +++ b/apps/web/tests/expected/steer-all/settled.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Use the ask_user_question tool to ask me exactly one question with id "checkpoint", question "Ready to continue?", header "Checkpoint", and options labeled "Yes" and "No". After I answer, reply with one short sentence acknowledging my answer and stop. {{clock}} - button "Copy" - button "1 tool call" diff --git a/apps/web/tests/goal-multi-turn-actions.e2e.ts b/apps/web/tests/goal-multi-turn-actions.e2e.ts index 9b6ebf857f..1361a476d3 100644 --- a/apps/web/tests/goal-multi-turn-actions.e2e.ts +++ b/apps/web/tests/goal-multi-turn-actions.e2e.ts @@ -155,9 +155,9 @@ describe('web e2e: Goal keeps one assistant action row per completed turn', () = expect(sessionEvents.flatMap(event => event.type === 'request/header' ? [event.data.reason] : [])).toEqual(['initial', 'series']) await expect.poll(() => page.locator('[data-turn-process]').count(), { timeout: 15_000 }).toBe(2) - expect(await page.getByRole('button', { name: 'System prompt' }).count()).toBe(2) + expect(await page.getByRole('button', { name: 'System prompt' }).count()).toBe(0) expect(await page.locator( - '[data-chat-flow-kind="system-prompt"][hidden="until-found"]', + '[data-chat-flow-kind="system-prompt"]', ).count()).toBe(0) const branchButtons = page.getByRole('button', { name: 'Branch into a new conversation' }) await expect.poll(() => branchButtons.count(), { timeout: 15_000 }).toBe(2) diff --git a/apps/web/tests/lifecycle-chrome.e2e.ts b/apps/web/tests/lifecycle-chrome.e2e.ts index 241d90707c..0576d26412 100644 --- a/apps/web/tests/lifecycle-chrome.e2e.ts +++ b/apps/web/tests/lifecycle-chrome.e2e.ts @@ -323,10 +323,12 @@ describe('web e2e: lifecycle & chrome (workspace flow / reload / dark mode)', () const originalViewport = page.viewportSize() ?? { width: 1680, height: 1000 } if (MODE !== 'record') await page.setViewportSize({ width: 480, height: 1000 }) const observedReasoning = Promise.withResolvers() + const reasoningComplete = Promise.withResolvers() const releaseStream = MODE === 'record' ? undefined : scaffold.ctx.on('llm/stream', async function* (_options, next) { let reasoning = false for await (const chunk of next()) { if (reasoning && chunk.type !== 'reasoning-delta') { + reasoningComplete.resolve(undefined) await observedReasoning.promise } if (chunk.type === 'reasoning-delta') reasoning = true @@ -338,17 +340,10 @@ describe('web e2e: lifecycle & chrome (workspace flow / reload / dark mode)', () if (MODE !== 'record') { const thinking = page.locator('[data-variant="think"][data-state="running"]') await expect.poll(() => thinking.getByRole('button').getAttribute('aria-expanded')).toBe('false') - const liveTail = thinking.locator('[data-follow-end]') - await expect.poll(async () => { - if (await liveTail.count() !== 1) return false - return await liveTail.evaluate((element) => { - const text = element.firstElementChild - if (!(text instanceof HTMLElement)) return false - const viewport = element.getBoundingClientRect() - const content = text.getBoundingClientRect() - return content.width > viewport.width && Math.abs(content.right - viewport.right) <= 1 - }) - }, { timeout: 10_000, interval: 10 }).toBe(true) + await reasoningComplete.promise + expect(await thinking.getAttribute('data-preview')).toBeNull() + expect(await thinking.getByRole('button').getAttribute('aria-expanded')).toBe('false') + expect(await thinking.locator('[data-streaming]').isVisible()).toBe(false) } observedReasoning.resolve(undefined) return await settled diff --git a/apps/web/tests/message-actions.e2e.ts b/apps/web/tests/message-actions.e2e.ts index fd4a0b2e9c..a4f07bb745 100644 --- a/apps/web/tests/message-actions.e2e.ts +++ b/apps/web/tests/message-actions.e2e.ts @@ -227,7 +227,7 @@ describe('web e2e: message IconActions and clocks on settled history', () => { await expect.poll( () => page.getByRole('button', { name: 'System prompt', exact: true }).count(), { timeout: 10_000 }, - ).toBe(2) + ).toBe(0) // Focus-reveal the footers (hover:hover keeps them opacity-hidden until // hover/focus-within). Branch renders only under assistant answers — user @@ -255,7 +255,10 @@ describe('web e2e: message IconActions and clocks on settled history', () => { const copy = page.getByRole('button', { name: 'Copy', exact: true }).last() const composer = page.locator('[data-composer-seat]') const tooltip = page.getByRole('tooltip', { name: 'Copy', exact: true }) + const originalViewport = page.viewportSize() + if (originalViewport === null) throw new Error('tooltip probe requires a fixed viewport') try { + await page.setViewportSize({ width: originalViewport.width, height: 600 }) // Grow the sticky seat upward so the bottom tooltip overlaps it without // depending on the fixture's resting composer height. await composer.evaluate((element) => { element.style.paddingTop = '48px' }) @@ -297,6 +300,7 @@ describe('web e2e: message IconActions and clocks on settled history', () => { await page.mouse.move(0, 0) if (await copy.count() > 0) await copy.evaluate((element) => { element.blur() }) if (await tooltip.count() > 0) await tooltip.waitFor({ state: 'hidden', timeout: 5_000 }) + await page.setViewportSize(originalViewport) } expect(tripwire.pageErrors).toEqual([]) }, 60_000) diff --git a/apps/web/tests/replay-round-trip.e2e.ts b/apps/web/tests/replay-round-trip.e2e.ts index 48b505f398..7604dba970 100644 --- a/apps/web/tests/replay-round-trip.e2e.ts +++ b/apps/web/tests/replay-round-trip.e2e.ts @@ -296,24 +296,13 @@ describe('web e2e: fresh round trip through the real assembly', () => { await compareOrRefreshGolden(UI_EXPANDED_EXPECTED, expanded, MODE) }) - it.skipIf(MODE === 'record')('renders the system prompt disclosure inside the expanded Turn process', async () => { + it.skipIf(MODE === 'record')('omits system prompt rows even when the Turn process is expanded', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-round-trip-system-prompt')) await expandTurnProcesses(page) - const disclosure = page.getByRole('button', { name: 'System prompt', exact: true }) - const body = page.locator('[data-system-prompt-body]') - await expect.poll(() => disclosure.count(), { timeout: 10_000 }).toBe(1) - await expect.poll(() => disclosure.getAttribute('aria-expanded')).toBe('false') - expect(await body.count()).toBe(0) - - await disclosure.click() - await expect.poll(() => disclosure.getAttribute('aria-expanded')).toBe('true') - const opaque = body.locator('[data-context-text]') - await expect.poll(() => opaque.count(), { timeout: 5_000 }).toBe(1) - expect(await opaque.textContent()).toContain('You are an AI agent powered by DeepSeek Harness.') - - await disclosure.click() - await expect.poll(() => disclosure.getAttribute('aria-expanded')).toBe('false') - await expect.poll(() => body.count()).toBe(0) + expect(sessionEvents.some(event => event.type === 'system/message')).toBe(true) + expect(await page.locator('[data-chat-flow-kind="system-prompt"]').count()).toBe(0) + expect(await page.getByRole('button', { name: 'System prompt', exact: true }).count()).toBe(0) + expect(await page.locator('[data-system-prompt-body]').count()).toBe(0) }) it.skipIf(MODE === 'record')('expands and collapses the reasoning fold from its click target', async () => { diff --git a/apps/web/tests/seeded-history.e2e.ts b/apps/web/tests/seeded-history.e2e.ts index b31b33bba0..e63471911d 100644 --- a/apps/web/tests/seeded-history.e2e.ts +++ b/apps/web/tests/seeded-history.e2e.ts @@ -721,24 +721,21 @@ describe('web e2e: seeded history renders through cold resume', () => { if (bodyError !== undefined) throw bodyError }) - it.skipIf(MODE === 'record')('an Access-chip switch lands one command row: bare name, non-repeating settlement text', async () => { + it.skipIf(MODE === 'record')('an Access-chip switch persists its command without adding a Chat row', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-command-row')) - // The Access chip submits `/permission ` — a host command with no - // model call, so the settled row renders keylessly over this cold history. - // The row copy is the assertion: `permission · preset read-only`, - // where neither half repeats the other (the dispatched `/` and its - // argument stay out of the title, and the settlement text never restates - // the command's own name). await page.getByRole('button', { name: 'Access mode, current: Workspace Write' }).click() await page.getByRole('menuitem', { name: 'Read Only' }).click() const access = page.getByRole('button', { name: 'Access mode, current: Read Only' }) await expect.poll(() => access.isEnabled(), { timeout: 10_000 }).toBe(true) - // Scoped to the row itself, so unrelated page text that happens to read - // `permission` (a future resident slash menu) cannot satisfy or break it. const row = page.locator('[data-variant="others"]').filter({ hasText: 'preset read-only' }) - await expect.poll(() => row.count(), { timeout: 10_000 }).toBe(1) - expect(await row.getByText('permission', { exact: true }).count()).toBe(1) - expect(await row.getByText('/permission read-only', { exact: true }).count()).toBe(0) + expect(await row.count()).toBe(0) + const agent = scaffold.ctx.agents.get(SessionId(SEED_ID)) + if (agent === undefined) throw new Error('seeded session did not attach an agent') + const events = agent.session.snapshotEvents() + const run = events.findLast(event => event.type === 'command/run' && event.data.name === 'permission') + if (run?.type !== 'command/run') throw new Error('permission command was not persisted') + expect(events.find(event => event.type === 'command/done' && event.data.commandId === run.data.commandId)?.data) + .toMatchObject({ kind: 'success', text: 'preset read-only' }) const snapshot = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)) .split(SEED_ID).join('{{seededId}}') await compareOrRefreshGolden(COMMAND_ROW_EXPECTED, snapshot, MODE) diff --git a/apps/web/tests/settings-chrome.e2e.ts b/apps/web/tests/settings-chrome.e2e.ts index 0c6e79308a..050a928221 100644 --- a/apps/web/tests/settings-chrome.e2e.ts +++ b/apps/web/tests/settings-chrome.e2e.ts @@ -548,17 +548,20 @@ describe('web e2e: settings modal and General preferences', () => { expect(tripwire.pageErrors).toEqual([]) }, 90_000) - it('persists the completed-Turn transcript mode across reload', async () => { + it.each([ + ['detailed', '详细'], ['expanded', '完全展开'], + ] as const)('persists the %s work-details mode across reload', async (mode, label) => { onTestFailed(() => saveFailureShot(page, 'web-e2e-settings-transcript-view')) await page.getByRole('button', { name: '设置', exact: true }).click() const dialog = page.getByRole('dialog', { name: '设置' }) await dialog.waitFor({ timeout: 10_000 }) - await dialog.getByText('对话显示', { exact: true }).waitFor({ timeout: 10_000 }) - await dialog.getByRole('button', { name: '紧凑', exact: true }).click() - await page.getByRole('menuitem', { name: '标准', exact: true }).click() - await dialog.getByRole('button', { name: '标准', exact: true }).waitFor({ timeout: 10_000 }) + await dialog.getByText('工作过程展示', { exact: true }).waitFor({ timeout: 10_000 }) + const details = dialog.getByText('工作过程展示', { exact: true }).locator('../..') + await details.getByRole('button', { name: '简洁', exact: true }).click() + await page.getByRole('menuitem', { name: label, exact: true }).click() + await details.getByRole('button', { name: label, exact: true }).waitFor({ timeout: 10_000 }) await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 }) - .toMatch(/ui-chat:\n\s+transcriptView: normal/) + .toContain(`transcriptView: ${mode}`) await page.keyboard.press('Escape') const warningStart = tripwire.warnings.length @@ -567,11 +570,12 @@ describe('web e2e: settings modal and General preferences', () => { acknowledgeReloadConnectionLoss(tripwire, warningStart) await page.getByRole('button', { name: '设置', exact: true }).click() const reloaded = page.getByRole('dialog', { name: '设置' }) - await reloaded.getByRole('button', { name: '标准', exact: true }).waitFor({ timeout: 10_000 }) + const restoredDetails = reloaded.getByText('工作过程展示', { exact: true }).locator('../..') + await restoredDetails.getByRole('button', { name: label, exact: true }).waitFor({ timeout: 10_000 }) - await reloaded.getByRole('button', { name: '标准', exact: true }).click() - await page.getByRole('menuitem', { name: '紧凑', exact: true }).click() - await reloaded.getByRole('button', { name: '紧凑', exact: true }).waitFor({ timeout: 10_000 }) + await restoredDetails.getByRole('button', { name: label, exact: true }).click() + await page.getByRole('menuitem', { name: '简洁', exact: true }).click() + await restoredDetails.getByRole('button', { name: '简洁', exact: true }).waitFor({ timeout: 10_000 }) await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 }) .toMatch(/ui-chat:\n\s+transcriptView: compact/) await page.keyboard.press('Escape') diff --git a/apps/web/tests/turn-tail-actions.e2e.ts b/apps/web/tests/turn-tail-actions.e2e.ts index 7ea13e1c9c..f4f33e8f1d 100644 --- a/apps/web/tests/turn-tail-actions.e2e.ts +++ b/apps/web/tests/turn-tail-actions.e2e.ts @@ -232,7 +232,9 @@ describe('web e2e: assistant IconActions wait for the turn to end', () => { expect(tripwire.warnings).toEqual([]) }, 60_000) - it.skipIf(MODE === 'record')('switches a completed Turn between Compact and Normal', async () => { + it.skipIf(MODE === 'record').each([ + ['detailed', 'Detailed'], ['expanded', 'Expanded'], + ] as const)('preserves whole-Turn folding in %s mode', async (mode, label) => { await launch() onTestFailed(() => saveFailureShot(page, 'web-e2e-turn-process-setting')) const { settled } = await sendPrompt() @@ -245,18 +247,21 @@ describe('web e2e: assistant IconActions wait for the turn to end', () => { await page.getByRole('button', { name: 'Settings', exact: true }).click() const dialog = page.getByRole('dialog', { name: 'Settings' }) - await dialog.getByRole('button', { name: 'Compact', exact: true }).click() - await page.getByRole('menuitem', { name: 'Normal', exact: true }).click() + await dialog.getByText('Work details', { exact: true }).locator('../..') + .getByRole('button', { name: 'Compact', exact: true }).click() + await page.getByRole('menuitem', { name: label, exact: true }).click() await page.keyboard.press('Escape') - await expect.poll(() => process.count(), { timeout: 10_000 }).toBe(0) - await tool.waitFor({ state: 'visible', timeout: 10_000 }) + expect(await process.count()).toBe(1) + expect(await process.getAttribute('aria-expanded')).toBe('false') + expect(await tool.isVisible()).toBe(false) await expect.poll(async () => readFile(join(scaffold!.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 }) - .toMatch(/ui-chat:\n\s+transcriptView: normal/) + .toContain(`transcriptView: ${mode}`) await page.getByRole('button', { name: 'Settings', exact: true }).click() const restored = page.getByRole('dialog', { name: 'Settings' }) - await restored.getByRole('button', { name: 'Normal', exact: true }).click() + await restored.getByText('Work details', { exact: true }).locator('../..') + .getByRole('button', { name: label, exact: true }).click() await page.getByRole('menuitem', { name: 'Compact', exact: true }).click() await page.keyboard.press('Escape') await process.waitFor({ timeout: 10_000 }) diff --git a/packages/client/ui-chat/tests/chat-view.client.spec.tsx b/packages/client/ui-chat/tests/chat-view.client.spec.tsx index 9cae3426ea..1ee50e0265 100644 --- a/packages/client/ui-chat/tests/chat-view.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-view.client.spec.tsx @@ -1472,6 +1472,7 @@ describe('ChatView', () => { assistant(5, 'final answer', 1, 2), ], turnEnds: new Map([[1, 6]]), + turnTimings: new Map([[1, { startTime: 0, endTime: 6_000 }]]), }) const view = render() const contextRow = view.container.querySelector('[data-chat-flow-kind="context"]') @@ -1485,18 +1486,16 @@ describe('ChatView', () => { expect(members.map(member => member.getAttribute('hidden'))).toEqual([null, null, null]) }) - it('keeps the first System prompt above User and outside Process through completion and expansion', () => { + it('omits the System prompt through Turn completion and process expansion', () => { const builder = new ChatSnapshotBuilder() const initial = withSystemPrompt(chatSnapshotFixture({ nodes: [userInTurn(2, 'question', 1), context(3, 'runtime policy', 1)], + turnTimings: new Map([[1, { startTime: 0 }]]), }), builder) const h = makeHarness({ chat: initial }, { running: true }) const view = render() - const promptRow = view.container.querySelector('[data-chat-flow-kind="system-prompt"]')! - - expect(renderedFlowKinds(view.container)).toEqual(['system-prompt', 'user', 'context']) - expect(promptRow.getAttribute('hidden')).toBeNull() - expect(promptRow.hasAttribute('data-turn-process-member')).toBe(false) + expect(renderedFlowKinds(view.container)).toEqual(['user', 'context']) + expect(view.container.querySelector('[data-chat-flow-kind="system-prompt"]')).toBeNull() act(() => { h.set({ @@ -1506,15 +1505,15 @@ describe('ChatView', () => { context(3, 'runtime policy', 1), reasoningAssistant(4, 'inspect', 1, 1), ], + turnTimings: new Map([[1, { startTime: 0 }]]), }), builder), running: true, }) }) expect(renderedFlowKinds(view.container)).toEqual([ - 'system-prompt', 'user', 'turn-process', 'context', 'assistant-step', + 'user', 'turn-process', 'context', 'assistant-step', ]) - expect(view.container.querySelector('[data-chat-flow-kind="system-prompt"]')).toBe(promptRow) - expect(promptRow.getAttribute('hidden')).toBeNull() + expect(view.container.querySelector('[data-chat-flow-kind="system-prompt"]')).toBeNull() act(() => { h.set({ @@ -1526,6 +1525,7 @@ describe('ChatView', () => { assistant(6, 'final answer', 1, 2), ], turnEnds: new Map([[1, 7]]), + turnTimings: new Map([[1, { startTime: 0, endTime: 7_000 }]]), }), builder), running: false, }) @@ -1533,19 +1533,18 @@ describe('ChatView', () => { const toggle = turnProcessControl(view.container)! const members = [...view.container.querySelectorAll('[data-turn-process-member]')] expect(renderedFlowKinds(view.container)).toEqual([ - 'system-prompt', 'user', 'turn-process', 'context', 'assistant-step', 'assistant-step', 'turn-tail', + 'user', 'turn-process', 'context', 'assistant-step', 'assistant-step', 'turn-tail', ]) expect(toggle.getAttribute('aria-expanded')).toBe('false') - expect(promptRow.getAttribute('hidden')).toBeNull() - expect(promptRow.hasAttribute('data-turn-process-member')).toBe(false) + expect(view.container.querySelector('[data-chat-flow-kind="system-prompt"]')).toBeNull() expect(members.map(member => member.dataset.chatFlowKind)).toEqual(['context', 'assistant-step']) expect(members.map(member => member.getAttribute('hidden'))).toEqual(['until-found', 'until-found']) fireEvent.click(toggle) expect(renderedFlowKinds(view.container)).toEqual([ - 'system-prompt', 'user', 'turn-process', 'context', 'assistant-step', 'assistant-step', 'turn-tail', + 'user', 'turn-process', 'context', 'assistant-step', 'assistant-step', 'turn-tail', ]) - expect(promptRow.getAttribute('hidden')).toBeNull() + expect(view.container.querySelector('[data-chat-flow-kind="system-prompt"]')).toBeNull() expect(members.map(member => member.getAttribute('hidden'))).toEqual([null, null]) }) @@ -1553,6 +1552,7 @@ describe('ChatView', () => { const h = makeHarness({ nodes: [user(1, 'question'), context(2, 'runtime policy', 1), assistant(3, 'final answer', 1, 1)], turnEnds: new Map([[1, 4]]), + turnTimings: new Map([[1, { startTime: 0, endTime: 4_000 }]]), }) const view = render() const toggle = view.getByRole('button', { name: '已思考' }) @@ -1607,6 +1607,7 @@ describe('ChatView', () => { nodes: [user(1, 'question'), process], partial: { turn: 1, step: 2, blocks: [{ kind: 'text', text: 'streaming answer' }] }, running: true, + turnTimings: new Map([[1, { startTime: 0 }]]), }) const view = render() expect(turnProcessControl(view.container)).toBeNull() @@ -1625,11 +1626,12 @@ describe('ChatView', () => { expect(processRow.getAttribute('hidden')).toBe('until-found') }) - it('switches completed Turns between the persisted Normal and Compact modes', () => { + it('preserves whole-Turn folding and manual expansion across work-details modes', () => { const process = assistant(2, 'inspect', 1, 1) const h = makeHarness({ nodes: [user(1, 'question'), process, assistant(4, 'final answer', 1, 2)], turnEnds: new Map([[1, 5]]), + turnTimings: new Map([[1, { startTime: 0, endTime: 5_000 }]]), }) const view = render() const processRow = view.getByText('inspect').closest('[data-chat-flow-kind="assistant-step"]') as HTMLElement @@ -1637,13 +1639,20 @@ describe('ChatView', () => { expect(turnProcessControl(view.container)?.getAttribute('aria-expanded')).toBe('false') expect(processRow.getAttribute('hidden')).toBe('until-found') - act(() => { h.setTranscriptView('detailed') }) - expect(turnProcessControl(view.container)).toBeNull() - expect(processRow.getAttribute('hidden')).toBeNull() - - act(() => { h.setTranscriptView('compact') }) - expect(turnProcessControl(view.container)?.getAttribute('aria-expanded')).toBe('false') - expect(processRow.getAttribute('hidden')).toBe('until-found') + const toggle = turnProcessControl(view.container)! + for (const mode of ['detailed', 'expanded', 'compact'] as const) { + act(() => { h.setTranscriptView(mode) }) + expect(turnProcessControl(view.container)).toBe(toggle) + expect(toggle.getAttribute('aria-expanded')).toBe('false') + expect(processRow.getAttribute('hidden')).toBe('until-found') + } + fireEvent.click(toggle) + for (const mode of ['detailed', 'expanded', 'compact'] as const) { + act(() => { h.setTranscriptView(mode) }) + expect(turnProcessControl(view.container)).toBe(toggle) + expect(toggle.getAttribute('aria-expanded')).toBe('true') + expect(processRow.getAttribute('hidden')).toBeNull() + } }) it('folds final-step reasoning under the fallback title when every summary count is zero', () => { @@ -1654,7 +1663,11 @@ describe('ChatView', () => { { kind: 'text' as const, text: 'final answer' }, ], } - const h = makeHarness({ nodes: [user(1, 'question'), final], turnEnds: new Map([[1, 4]]) }) + const h = makeHarness({ + nodes: [user(1, 'question'), final], + turnEnds: new Map([[1, 4]]), + turnTimings: new Map([[1, { startTime: 0, endTime: 4_000 }]]), + }) const view = render() const toggle = view.getByRole('button', { name: '已思考' }) const reasoning = view.container.querySelector('[data-turn-process-inline]') @@ -1667,7 +1680,10 @@ describe('ChatView', () => { it('folds a completed Turn even while the reader is away from the tail', () => { const first = assistant(2, 'first answer', 1, 1) - const h = makeHarness({ nodes: [user(1, 'question'), first], running: true }) + const h = makeHarness({ + nodes: [user(1, 'question'), first], running: true, + turnTimings: new Map([[1, { startTime: 0 }]]), + }) const view = render() const scroller = view.container.querySelector('[class*="scroll"]') as HTMLDivElement Object.defineProperty(scroller, 'scrollHeight', { value: 1_000, writable: true }) @@ -1689,6 +1705,7 @@ describe('ChatView', () => { const h = makeHarness({ nodes: [user(1, 'question'), context(2, 'runtime policy', 1)], running: true, + turnTimings: new Map([[1, { startTime: 0 }]]), }) const view = render() const scroller = view.container.querySelector('[class*="scroll"]') as HTMLDivElement @@ -1716,6 +1733,7 @@ describe('ChatView', () => { const h = makeHarness({ nodes: [user(1, 'question'), context(2, 'runtime policy', 1)], running: true, + turnTimings: new Map([[1, { startTime: 0 }]]), }) const view = render() const contextToggle = view.getByRole('button', { name: '上下文注入' }) @@ -1743,7 +1761,7 @@ describe('ChatView', () => { expect(contextRow?.getAttribute('hidden')).toBe('until-found') }) - it('keeps a foldable closed Turn fully visible while history is partial', () => { + it('withholds folding until the Turn start arrives even when older history remains', () => { const h = makeHarness({ nodes: [ user(1, 'question'), @@ -1762,6 +1780,13 @@ describe('ChatView', () => { expect(contextRow?.hasAttribute('data-turn-process-member')).toBe(false) act(() => { h.set({ hasMore: false }) }) + expect(turnProcessControl(view.container)).toBeNull() + expect(contextRow?.getAttribute('hidden')).toBeNull() + + act(() => { h.set({ + hasMore: true, + turnTimings: new Map([[1, { startTime: 0, endTime: 5_000 }]]), + }) }) const toggle = turnProcessControl(view.container)! expect(toggle.getAttribute('aria-expanded')).toBe('false') expect(contextRow?.getAttribute('hidden')).toBe('until-found') @@ -1785,6 +1810,7 @@ describe('ChatView', () => { assistant(10, 'visible answer', 2), ], turnEnds: new Map([[1, 5]]), + turnTimings: new Map([[1, { startTime: 0, endTime: 5_000 }]]), hasMore: false, }) }) @@ -1808,6 +1834,7 @@ describe('ChatView', () => { assistant(4, 'final answer', 1, 2), ], turnEnds: new Map([[1, 5]]), + turnTimings: new Map([[1, { startTime: 0, endTime: 5_000 }]]), }) const process = source.nodes.values() .find((candidate): candidate is ChatNode<'turn-process'> => candidate.kind === 'turn-process') @@ -1863,6 +1890,7 @@ describe('ChatView', () => { const h = makeHarness({ nodes: [user(1, 'question'), first, assistant(4, 'new answer', 1, 2)], turnEnds: new Map([[1, 5]]), + turnTimings: new Map([[1, { startTime: 0, endTime: 5_000 }]]), }) const view = render(, { container: host }) fireEvent.click(turnProcessControl(view.container)!) diff --git a/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts b/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts index f116edab09..90c9c79b0a 100644 --- a/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts +++ b/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts @@ -166,6 +166,12 @@ function node(value: ChatSnapshot, kind: string): ChatConversationViewNode | und return value.nodes.values().find(candidate => candidate.kind === kind) } +function promptNodes(value: ChatSnapshot): ChatConversationViewNode[] { + const prompts = value.nodes.values().filter(candidate => candidate.kind === 'system-prompt') + for (const prompt of prompts) expect(value.order).not.toContain(prompt.key) + return prompts.sort((left, right) => left.anchorSeq - right.anchorSeq) +} + function textMessage(id: string, text: string) { return { id, @@ -319,6 +325,42 @@ describe('built-in conversation node Definitions', () => { expect(hasAssistantReplyContent([{ kind: 'other', block: { type: 'future' } }])).toBe(true) }) + it.each(['replay', 'live', 'prepend'] as const)('hides permission commands but retains their data and ordinary Context (%s)', (mode) => { + const entries = [ + at(1, 'command/run', { commandId: 'permission-1', name: 'permission', source: { kind: 'user' } }), + at(2, 'command/done', { commandId: 'permission-1', kind: 'success', text: 'Granted' }), + at(3, 'command/run', { commandId: 'plan-1', name: 'plan', source: { kind: 'user' } }), + at(4, 'command/done', { commandId: 'plan-1', kind: 'success', text: 'Plan mode' }), + at(5, 'turn/start', { turn: 1 }), + at(6, 'step/start', { turn: 1, step: 1 }), + at(7, 'user/message', { + ...textMessage('context-1', 'workspace context'), + source: { kind: 'context' }, + }, { surfaceOp: 'append' }), + ] + const value = assembler(mode === 'replay' ? entries : []) + if (mode === 'live') { + for (const entry of entries) { + value.append(entry) + value.flush() + } + } else if (mode === 'prepend') { + value.replaceWindow(entries.slice(1), true) + value.flush() + expect(node(snapshot(value), 'command')?.data).toMatchObject({ name: null }) + value.prepend(entries.slice(0, 1), false) + value.flush() + } + const current = snapshot(value) + const visible = current.order.map(key => current.nodes.get(key)) + expect(visible.map(candidate => candidate?.kind)).toEqual(['command', 'context']) + expect(visible[0]?.data).toMatchObject({ name: 'plan' }) + expect(current.nodes.values().filter(candidate => candidate.kind === 'command')).toHaveLength(2) + expect(node(current, 'command')?.data).toMatchObject({ + name: 'permission', outcome: { kind: 'success', text: 'Granted' }, + }) + }) + it('projects one reversible process window before the finalized answer', () => { const value = assembler([ at(1, 'turn/start', { turn: 1 }), @@ -1543,7 +1585,7 @@ describe('built-in conversation node Definitions', () => { expect(current.nodes.values().filter(candidate => candidate.kind === 'unknown')).toEqual([]) }) - it('shows a complete appended prompt at the start of a headerless window', () => { + it('retains a complete appended prompt at the start of a headerless window', () => { const value = assembler([ systemUpdateAt(10, '# Known prompt', 2, 1), at(11, 'user/message', textMessage('window-user', 'continue'), { surfaceOp: 'append' }), @@ -1558,8 +1600,8 @@ describe('built-in conversation node Definitions', () => { ], false) value.flush() const restored = snapshot(value) - expect(restored.order.map(key => restored.nodes.get(key)).filter(candidate => candidate?.kind === 'system-prompt') - .map(candidate => candidate?.data)).toEqual([{ text: '# Original' }, { text: '# Known prompt', update: true }]) + expect(promptNodes(restored).map(candidate => candidate.data)) + .toEqual([{ text: '# Original' }, { text: '# Known prompt', update: true }]) }) it('withholds windowed replacement prompts until prepend resolves their positions', () => { @@ -1595,10 +1637,7 @@ describe('built-in conversation node Definitions', () => { ] const promptTexts = (value: ConversationNodeAssembler) => { const restored = snapshot(value) - return restored.order.flatMap((key) => { - const candidate = restored.nodes.get(key) - return candidate?.kind === 'system-prompt' ? [candidate.data] : [] - }) + return promptNodes(restored).map(candidate => candidate.data) } windowed.prepend(older, false) windowed.flush() @@ -1608,7 +1647,7 @@ describe('built-in conversation node Definitions', () => { expect(promptTexts(nodeless)).toEqual([{ text: '# Original prompt' }, { text: '# Original prompt' }]) }) - it('shows the system node text as the request prompt card before the request messages', () => { + it('retains the request prompt without adding it to visible Chat rows', () => { const value = assembler([ at(1, 'turn/start', { turn: 1 }), at(2, 'step/start', { turn: 1, step: 1 }), @@ -1626,7 +1665,6 @@ describe('built-in conversation node Definitions', () => { const current = snapshot(value) expect(current.order.map(key => current.nodes.get(key)?.kind)).toEqual([ - 'system-prompt', 'user', 'context', ]) @@ -1675,8 +1713,7 @@ describe('built-in conversation node Definitions', () => { } } const current = snapshot(value) - expect(current.order.map(key => current.nodes.get(key)).filter(candidate => candidate?.kind === 'system-prompt') - .map(candidate => candidate?.data)).toEqual([ + expect(promptNodes(current).map(candidate => candidate.data)).toEqual([ { text: 'A' }, { text: 'B', update: true }, { text: 'A' }, ]) }) @@ -1704,15 +1741,15 @@ describe('built-in conversation node Definitions', () => { ]) const current = snapshot(value) - expect(current.order.map(key => current.nodes.get(key)?.kind)).toEqual(['system-prompt', 'user']) + expect(current.order.map(key => current.nodes.get(key)?.kind)).toEqual(['user']) value.append(systemAt(5, '# Replaced', 3)) value.flush() const replaced = snapshot(value) - expect(replaced.order.map(key => replaced.nodes.get(key)?.kind)).toEqual(['system-prompt', 'user']) + expect(replaced.order.map(key => replaced.nodes.get(key)?.kind)).toEqual(['user']) }) - it('presents an in-history prompt update as its own card and lets no same-step header repeat it', () => { + it('retains an in-history prompt update without duplicating it at the same-step header', () => { const value = assembler([ at(1, 'turn/start', { turn: 1 }), at(2, 'step/start', { turn: 1, step: 1 }), @@ -1731,19 +1768,14 @@ describe('built-in conversation node Definitions', () => { ]) const cards = () => { const current = snapshot(value) - return current.order.flatMap((key) => { - const candidate = current.nodes.get(key) - return candidate?.kind === 'system-prompt' ? [[candidate.anchorSeq, candidate.data]] : [] - }) + return promptNodes(current).map(candidate => [candidate.anchorSeq, candidate.data]) } - // The update is the model-visible change at its position; node 0 keeps its card. expect(cards()).toEqual([ [1, { text: '# System' }], [10, { text: '# Updated', update: true }], ]) - // A series header in the same step shows nothing more: the update card already carries the text. value.append(at(12, 'request/header', { reason: 'series', startsSeries: true, @@ -1752,7 +1784,6 @@ describe('built-in conversation node Definitions', () => { value.flush() expect(cards()).toHaveLength(2) - // A later series header presents the effective prompt again, as any series start does. value.append(at(13, 'step/end', { turn: 2, step: 1 })) value.append(at(14, 'step/start', { turn: 2, step: 2 })) value.append(at(15, 'request/header', { @@ -1784,10 +1815,11 @@ describe('built-in conversation node Definitions', () => { ]) const current = snapshot(value) - expect(current.order.map(key => current.nodes.get(key)?.kind)).toEqual(['system-prompt', 'user']) + expect(current.order.map(key => current.nodes.get(key)?.kind)).toEqual(['user']) + expect(promptNodes(current).map(candidate => candidate.data)).toEqual([{ text: '# System' }]) }) - it('keeps the initial system prompt before the opening User as Turn process state changes', () => { + it('keeps the system prompt out of Chat order as Turn process state changes', () => { const value = assembler([ at(1, 'turn/start', { turn: 1 }), at(2, 'step/start', { turn: 1, step: 1 }), @@ -1808,14 +1840,14 @@ describe('built-in conversation node Definitions', () => { } const promptKey = node(snapshot(value), 'system-prompt')?.key - expect(kinds()).toEqual(['system-prompt', 'user', 'context']) + expect(kinds()).toEqual(['user', 'context']) value.append(at(7, 'assistant/live-chunk', { turn: 1, step: 1, chunk: { type: 'reasoning-delta', index: 0, text: 'thinking' }, })) value.flush() expect(kinds()).toEqual([ - 'system-prompt', 'user', 'turn-process', 'context', 'assistant-step', + 'user', 'turn-process', 'context', 'assistant-step', ]) value.append(at(8, 'step/end', { turn: 1, step: 1 })) @@ -1828,7 +1860,7 @@ describe('built-in conversation node Definitions', () => { value.flush() expect(kinds()).toEqual([ - 'system-prompt', 'user', 'turn-process', 'context', 'assistant-step', 'assistant-step', 'turn-tail', + 'user', 'turn-process', 'context', 'assistant-step', 'assistant-step', 'turn-tail', ]) expect(node(snapshot(value), 'system-prompt')?.key).toBe(promptKey) }) @@ -1855,7 +1887,8 @@ describe('built-in conversation node Definitions', () => { const candidate = current.nodes.get(key) return candidate?.kind === 'system-prompt' || candidate?.kind === 'user' ? [candidate] : [] }) - expect(ordered.map(candidate => candidate.kind)).toEqual(['system-prompt', 'user', 'user']) + expect(ordered.map(candidate => candidate.kind)).toEqual(['user', 'user']) + expect(promptNodes(current).map(candidate => candidate.data)).toEqual([{ text: '# System' }]) }) it('places a withheld replacement prompt after prepend supplies its original node', () => { @@ -1892,10 +1925,7 @@ describe('built-in conversation node Definitions', () => { windowed.flush() const restored = snapshot(windowed) - const prompts = restored.order.flatMap((key) => { - const candidate = restored.nodes.get(key) - return candidate?.kind === 'system-prompt' ? [candidate] : [] - }) + const prompts = promptNodes(restored) expect(prompts.map(candidate => candidate.anchorSeq)).toEqual([1, 10]) expect(prompts.at(-1)?.data).toEqual({ text: windowedSystem }) expect(restored.nodes.get(user.key)).toBeDefined() @@ -1936,11 +1966,8 @@ describe('built-in conversation node Definitions', () => { const candidate = current.nodes.get(key) return candidate?.kind === 'system-prompt' || candidate?.kind === 'user' ? [candidate] : [] }) - expect(ordered.map(candidate => candidate?.kind)).toEqual([ - 'system-prompt', 'user', 'system-prompt', 'system-prompt', 'user', - ]) - expect(ordered.filter(candidate => candidate?.kind === 'system-prompt') - .map(candidate => candidate?.anchorSeq)).toEqual([1, 7, 10]) + expect(ordered.map(candidate => candidate.kind)).toEqual(['user', 'user']) + expect(promptNodes(current).map(candidate => candidate.anchorSeq)).toEqual([1, 7, 10]) }) it('associates each direct message with its immediately following session recall', () => { diff --git a/packages/client/ui-chat/tests/presentation-policy.client.spec.tsx b/packages/client/ui-chat/tests/presentation-policy.client.spec.tsx new file mode 100644 index 0000000000..c7070e147c --- /dev/null +++ b/packages/client/ui-chat/tests/presentation-policy.client.spec.tsx @@ -0,0 +1,64 @@ +// @vitest-environment jsdom +import { act, cleanup, render } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-test-runtime' +import type { TranscriptViewMode } from '../src/chat-settings.ts' +import { derivePresentationPolicy, presentationPolicyFor } from '../src/client/presentation-policy.ts' + +afterEach(cleanup) + +describe('Chat presentation policy', () => { + it.each([ + ['compact', 'collapsed', false], + ['detailed', 'collapsed', true], + ['expanded', 'none', true], + ] as const)('maps %s to stable presentation capabilities', (mode, stepGrouping, settledReasoningPreview) => { + const policy = presentationPolicyFor(mode) + expect(policy).toEqual({ mode, foldCompletedTurns: true, stepGrouping, settledReasoningPreview }) + expect(presentationPolicyFor(mode)).toBe(policy) + }) + + it('forwards mode notifications and removes the subscription on disposal', () => { + const mode = createSnapshotStore('compact') + const policy = derivePresentationPolicy(mode) + const listener = vi.fn() + const dispose = policy.subscribe(listener) + expect(policy.getSnapshot()).toBe(presentationPolicyFor('compact')) + mode.set('detailed') + expect(listener).toHaveBeenCalledTimes(1) + expect(policy.getSnapshot()).toBe(presentationPolicyFor('detailed')) + dispose() + mode.set('expanded') + expect(listener).toHaveBeenCalledTimes(1) + }) + + it('renders only consumers whose selected field changes', () => { + const mode = createSnapshotStore('compact') + const usePresentation = bindSnapshotSelector(derivePresentationPolicy(mode)) + const foldRender = vi.fn() + const previewRender = vi.fn() + function Fold() { + const fold = usePresentation(policy => policy.foldCompletedTurns) + foldRender(fold) + return {String(fold)} + } + function Preview() { + const preview = usePresentation(policy => policy.settledReasoningPreview) + previewRender(preview) + return {String(preview)} + } + render(<>) + expect(foldRender).toHaveBeenCalledTimes(1) + expect(previewRender).toHaveBeenCalledTimes(1) + act(() => { mode.set('detailed') }) + expect(foldRender).toHaveBeenCalledTimes(1) + expect(previewRender).toHaveBeenCalledTimes(2) + act(() => { mode.set('expanded') }) + expect(foldRender).toHaveBeenCalledTimes(1) + expect(previewRender).toHaveBeenCalledTimes(2) + act(() => { mode.set('compact') }) + expect(foldRender).toHaveBeenCalledTimes(1) + expect(previewRender).toHaveBeenCalledTimes(3) + }) +}) diff --git a/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx b/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx index e1f399208e..c729a91634 100644 --- a/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx +++ b/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx @@ -1,11 +1,15 @@ // @vitest-environment jsdom import { afterEach, describe, expect, it } from 'vitest' -import { cleanup, fireEvent, render } from '@testing-library/react' -import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { act, cleanup, fireEvent, render } from '@testing-library/react' +import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' import { zh } from '../src/client/locale.ts' import { AssistantMarkdown, type AssistantMarkdownProps } from '../src/client/chat/AssistantMarkdown.tsx' import { useDetailedPresentation } from './presentation-fixture.client.ts' +import type { TranscriptViewMode } from '../src/chat-settings.ts' +import { derivePresentationPolicy } from '../src/client/presentation-policy.ts' +import { ReasoningRow } from '../src/client/chat/ReasoningRow.tsx' afterEach(() => { cleanup() @@ -15,6 +19,59 @@ const t = makeTranslate(zh, commonZh) const renderMessageImages: AssistantMarkdownProps['renderMessageImages'] = () => null describe('ReasoningRow', () => { + it.each([ + ['', ''], + ['An unfinished line', ''], + ['A completed first line\nUnfinished continuation', 'A completed first line'], + ['First\nSecond\nThird\n', 'First'], + ['First\n\nNext unfinished', 'First'], + ['First\n\nNext complete\nDetails', 'Next complete'], + ['First\r\n \t\r\nNext complete\r\n', 'Next complete'], + ['First\n\n\n', 'First'], + ])('previews the completed paragraph first line for %j', (text, summary) => { + const view = render() + const root = view.container.querySelector('[data-variant="think"]')! + expect(root.querySelector('[class*="summaryText"]')?.textContent).toBe(summary) + expect(root.hasAttribute('data-preview')).toBe(summary !== '') + }) + + it('retains summaries and expanded Markdown when the work-details mode changes', () => { + const mode = createSnapshotStore('detailed') + const usePresentation = bindSnapshotSelector(derivePresentationPolicy(mode)) + const view = render() + const root = view.container.querySelector('[data-variant="think"]')! + const summary = view.getByText('First line') + const toggle = view.getByRole('button') + for (const next of ['compact', 'detailed', 'expanded', 'compact'] as const) { + act(() => { mode.set(next) }) + expect(view.getByText('First line')).toBe(summary) + expect(root.hasAttribute('data-preview')).toBe(next !== 'compact') + expect(root.querySelector('[data-markdown-variant]')).toBeNull() + } + fireEvent.click(toggle) + const body = view.getByText('Detailed body') + for (const next of ['detailed', 'expanded', 'compact'] as const) { + act(() => { mode.set(next) }) + expect(view.getByText('Detailed body')).toBe(body) + expect(toggle.getAttribute('aria-expanded')).toBe('true') + expect(root.hasAttribute('data-preview')).toBe(false) + } + }) + + it('keeps a running preview enabled in Compact and hides it on settlement without removing it', () => { + const mode = createSnapshotStore('compact') + const usePresentation = bindSnapshotSelector(derivePresentationPolicy(mode)) + const props = { text: 'First line\n', usePresentation, t } + const view = render() + const summary = view.getByText('First line') + const root = view.container.querySelector('[data-variant="think"]')! + expect(root.hasAttribute('data-preview')).toBe(true) + view.rerender() + expect(root.hasAttribute('data-preview')).toBe(false) + expect(view.getByText('First line')).toBe(summary) + }) + it.each([ { kind: 'text' as const, text: 'Answer' }, { kind: 'tool-call' as const, callId: 'call-1', name: 'read', argsRaw: '{}' }, @@ -44,38 +101,52 @@ describe('ReasoningRow', () => { expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('false') }) - it('follows the latest streaming line, then restores the settled first line', () => { + it('advances on completed paragraph first lines, then restores the settled first line', () => { const view = render( , ) expect(view.getByText('运行中')).toBeTruthy() expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('false') - expect(view.getByText('Newest reasoning tokens').parentElement?.getAttribute('data-follow-end')) + expect(view.getByText('Newest reasoning tokens').parentElement?.getAttribute('data-streaming')) .toBe('true') view.rerender( , ) - expect(view.getByText('Newest reasoning tokens keep arriving').parentElement - ?.getAttribute('data-follow-end')).toBe('true') + expect(view.getByText('Newest reasoning tokens').parentElement + ?.getAttribute('data-streaming')).toBe('true') + expect(view.queryByText('Checking boundaries')).toBeNull() + + const text = 'Inspect the session\nDetails\n\nNewest reasoning tokens\nMore details\n\nChecking boundaries\n' + view.rerender( + , + ) + expect(view.getByText('Checking boundaries')).toBeTruthy() + expect(view.queryByText('Newest reasoning tokens')).toBeNull() view.rerender( , @@ -83,7 +154,7 @@ describe('ReasoningRow', () => { const settledSummary = view.getByText('Inspect the session') expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('false') expect(view.queryByText('运行中')).toBeNull() - expect(settledSummary.parentElement?.hasAttribute('data-follow-end')).toBe(false) + expect(settledSummary.parentElement?.hasAttribute('data-streaming')).toBe(false) }) it('expands from either Think or the reasoning summary', () => { @@ -114,7 +185,7 @@ describe('ReasoningRow', () => { }, { label: 'streaming', - text: 'Inspect the session\n**Comparing checkout and merge bases**', + text: 'Inspect the session\n\n**Comparing checkout and merge bases**\n', streaming: true, }, ])('strips double-asterisk markers from the $label summary and renders body emphasis', ({ text, streaming }) => { diff --git a/packages/client/ui-chat/tests/transcript-view-row.client.spec.tsx b/packages/client/ui-chat/tests/transcript-view-row.client.spec.tsx index a5887a4e1e..6d578cb38f 100644 --- a/packages/client/ui-chat/tests/transcript-view-row.client.spec.tsx +++ b/packages/client/ui-chat/tests/transcript-view-row.client.spec.tsx @@ -55,28 +55,37 @@ function mount(mode: TranscriptViewMode = 'compact', dictionary: typeof en | typ describe('TranscriptViewRow', () => { it('explains the preference and shows Compact by default', () => { mount() - expect(screen.getByText('Conversation display')).toBeDefined() - expect(screen.getByText('Controls process content in completed turns')).toBeDefined() + expect(screen.getByText('Work details')).toBeDefined() + expect(screen.getByText('Controls how turns and steps expand by default')).toBeDefined() expect(screen.getByRole('button', { name: /Compact/ }).getAttribute('aria-expanded')).toBe('false') }) - it('selects Normal and follows the mirrored value', () => { + it.each([ + ['detailed', 'Detailed'], + ['expanded', 'Expanded'], + ] as const)('selects %s and follows the mirrored value', (mode, label) => { const b = mount() fireEvent.click(screen.getByRole('button', { name: /Compact/ })) - fireEvent.click(screen.getByRole('menuitem', { name: 'Normal' })) - expect(b.setTranscriptView).toHaveBeenCalledWith('normal') - const trigger = screen.getByRole('button', { name: /Normal/ }) + expect(screen.queryByRole('menuitem', { name: 'Normal' })).toBeNull() + fireEvent.click(screen.getByRole('menuitem', { name: label })) + expect(b.setTranscriptView).toHaveBeenCalledWith(mode) + const trigger = screen.getByRole('button', { name: label }) fireEvent.click(trigger) expect(screen.getByRole('menuitem', { name: 'Compact' })).toBeDefined() fireEvent.pointerDown(document.body) expect(screen.queryByRole('menuitem', { name: 'Compact' })).toBeNull() }) - it('shows the conversation-display values in Chinese', () => { - mount('compact', zh) - fireEvent.click(screen.getByRole('button', { name: '紧凑' })) - fireEvent.click(screen.getByRole('menuitem', { name: '标准' })) - expect(screen.getByRole('button', { name: '标准' })).toBeDefined() + it('shows all three work-detail values in Chinese', () => { + const b = mount('compact', zh) + expect(screen.getByText('工作过程展示')).toBeDefined() + fireEvent.click(screen.getByRole('button', { name: '简洁' })) + fireEvent.click(screen.getByRole('menuitem', { name: '详细' })) + expect(b.setTranscriptView).toHaveBeenLastCalledWith('detailed') + fireEvent.click(screen.getByRole('button', { name: '详细' })) + fireEvent.click(screen.getByRole('menuitem', { name: '完全展开' })) + expect(b.setTranscriptView).toHaveBeenLastCalledWith('expanded') + expect(screen.getByRole('button', { name: '完全展开' })).toBeDefined() }) }) diff --git a/packages/client/ui-primitives/tests/text-shimmer-styles.client.spec.ts b/packages/client/ui-primitives/tests/text-shimmer-styles.client.spec.ts new file mode 100644 index 0000000000..b416a1705f --- /dev/null +++ b/packages/client/ui-primitives/tests/text-shimmer-styles.client.spec.ts @@ -0,0 +1,16 @@ +/** CSS activity and reduced-motion rules that jsdom does not execute. */ +import { readFileSync } from 'node:fs' +import { describe, expect, it } from 'vitest' + +const css = readFileSync(new URL('../src/TextShimmer.module.css', import.meta.url), 'utf8') + +describe('TextShimmer styles', () => { + it('animates active text and disables motion and transparent fill for reduced motion', () => { + expect(css).toMatch(/\.root\[data-text-shimmer\]\s*\{[^}]*animation: dsh-text-shimmer/s) + expect(css).toMatch(/@keyframes dsh-text-shimmer\s*\{[^}]*background-position: 0% center/s) + const reduced = /@media \(prefers-reduced-motion: reduce\)\s*\{\s*\.root\[data-text-shimmer\]\s*\{([^}]+)\}/.exec(css)?.[1] + expect(reduced).toContain('background-image: none;') + expect(reduced).toContain('-webkit-text-fill-color: currentColor;') + expect(reduced).toContain('animation: none;') + }) +}) diff --git a/packages/client/ui-primitives/tests/text-shimmer.client.spec.tsx b/packages/client/ui-primitives/tests/text-shimmer.client.spec.tsx new file mode 100644 index 0000000000..5f6efdf805 --- /dev/null +++ b/packages/client/ui-primitives/tests/text-shimmer.client.spec.tsx @@ -0,0 +1,29 @@ +// @vitest-environment jsdom +import { cleanup, render } from '@testing-library/react' +import { afterEach, describe, expect, it } from 'vitest' +import { TextShimmer } from '../src/TextShimmer.tsx' + +afterEach(cleanup) + +describe('TextShimmer', () => { + it('retains its text span across activity, text, and owner-class changes', () => { + const view = render(Run) + const span = view.getByText('Run') + expect(span.tagName).toBe('SPAN') + expect(span.dataset.textShimmer).toBe('true') + expect(span.classList.contains('title')).toBe(true) + expect(span.style.getPropertyValue('--dsh-text-shimmer-spread')).toBe('24px') + + view.rerender(End) + expect(view.getByText('End')).toBe(span) + expect(span.hasAttribute('data-text-shimmer')).toBe(false) + expect(span.classList.contains('title')).toBe(false) + expect(span.style.getPropertyValue('--dsh-text-shimmer-spread')).toBe('24px') + + view.rerender(Running) + expect(view.getByText('Running')).toBe(span) + expect(span.dataset.textShimmer).toBe('true') + expect(span.style.getPropertyValue('--dsh-text-shimmer-spread')).toBe('56px') + }) + +}) diff --git a/packages/client/ui-skill/tests/browser-plugin.client.spec.ts b/packages/client/ui-skill/tests/browser-plugin.client.spec.ts index d45088b225..ead382b4ac 100644 --- a/packages/client/ui-skill/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-skill/tests/browser-plugin.client.spec.ts @@ -132,7 +132,7 @@ describe('apply', () => { expect(presentation.dictionaries).toEqual([{ namespace: 'skill', dictionaries: { zh: { - 'row.title': 'Skill', + 'row.title': '加载技能', 'row.running': '正在加载 skill', 'row.failed': 'skill 加载失败', 'row.stopped': 'skill 加载已中止', diff --git a/packages/client/ui-skill/tests/skill-row.client.spec.tsx b/packages/client/ui-skill/tests/skill-row.client.spec.tsx index da55917f84..053f78b4a9 100644 --- a/packages/client/ui-skill/tests/skill-row.client.spec.tsx +++ b/packages/client/ui-skill/tests/skill-row.client.spec.tsx @@ -51,7 +51,7 @@ describe('SkillRow', () => { it('renders a compact Bash-shaped summary and discloses the exact instructions', () => { const inspect = vi.fn() const view = render() - const row = screen.getByRole('button', { name: 'Skilldsh-manage-issues' }) + const row = screen.getByRole('button', { name: '加载技能dsh-manage-issues' }) expect(row.getAttribute('aria-expanded')).toBe('false') expect(view.container.querySelector('[data-tool="skill"]')?.getAttribute('data-state')).toBe('ok') expect(view.container.querySelector('[data-tool="skill"] svg')?.getAttribute('width')).toBe('14') @@ -95,7 +95,7 @@ describe('SkillRow', () => { isError: true, error: { name: 'SkillError', code: 'missing' }, }))} />) - const row = screen.getByRole('button', { name: 'skill 加载失败SkillSkillError: missing resource' }) + const row = screen.getByRole('button', { name: 'skill 加载失败加载技能SkillError: missing resource' }) expect(view.container.querySelector('[data-tool="skill"]')?.getAttribute('data-state')).toBe('error') expect(view.container.querySelector('[data-tool="skill"] > div > span:first-child svg')).not.toBeNull() expect(view.container.querySelector('[data-tool="skill"] [data-state]')).toBeNull() @@ -128,7 +128,7 @@ describe('SkillRow', () => { isError: true, error: { name: 'SkillError', code: 'missing' }, }))} />) - const errorRow = screen.getByRole('button', { name: 'skill 加载失败SkillSkillError: missing' }) + const errorRow = screen.getByRole('button', { name: 'skill 加载失败加载技能SkillError: missing' }) fireEvent.click(errorRow) expect(screen.getAllByText('SkillError: missing')).toHaveLength(2) }) diff --git a/packages/client/ui-tool/tests/coverage-tails.client.spec.tsx b/packages/client/ui-tool/tests/coverage-tails.client.spec.tsx index 80615b752f..8254a70476 100644 --- a/packages/client/ui-tool/tests/coverage-tails.client.spec.tsx +++ b/packages/client/ui-tool/tests/coverage-tails.client.spec.tsx @@ -48,7 +48,7 @@ describe('Tool presentation tails', () => { ) expect(view.queryByTestId('icon')).not.toBeNull() const summary = view.getByText('s') - expect(summary.className).toContain('stoppedSummary') + expect(summary.parentElement?.className).toContain('stoppedSummary') }) it('a settled others-variant row renders the sparkle icon in the leading slot', () => { @@ -76,7 +76,7 @@ describe('Tool presentation tails', () => { } const view = render() const row = view.container.querySelector('[data-sample="bash"]')! - expect(row.textContent).toContain('Bash') + expect(row.textContent).toContain('运行命令') expect(row.textContent).toContain('Build') expect(row.getAttribute('data-clickable')).toBeNull() }) @@ -99,7 +99,7 @@ describe('Tool presentation tails', () => { const runningView = render() expect(runningView.container.querySelector('[data-state="running"]')).not.toBeNull() - expect(runningView.getByText('Bash')).toBeTruthy() + expect(runningView.getByText('运行命令')).toBeTruthy() expect(runningView.getByText('List')).toBeTruthy() runningView.unmount() @@ -107,14 +107,15 @@ describe('Tool presentation tails', () => { expect(errorView.container.querySelector('[data-sample="bash"]')).not.toBeNull() expect(errorView.container.querySelector('[data-state="error"]')).not.toBeNull() expect(errorView.container.querySelector('[data-state="error"] svg')).not.toBeNull() - expect(errorView.getByText('Bash')).toBeTruthy() + expect(errorView.getByText('运行命令')).toBeTruthy() expect(errorView.container.querySelector('[class*="_errorSummary_"]')).not.toBeNull() errorView.unmount() const stoppedView = render() expect(stoppedView.container.querySelector('[data-state="stopped"]')).not.toBeNull() expect(stoppedView.container.querySelector('[data-state="stopped"] svg')).not.toBeNull() - const stoppedSummary = stoppedView.getByText('已停止') - expect(stoppedSummary.className).toContain('stoppedSummary') + const stoppedSummary = stoppedView.getByRole('button').querySelector('[class*="_stoppedSummary_"]') + expect(stoppedSummary?.textContent).toBe('已停止') + expect(stoppedView.getAllByText('已停止')).toHaveLength(2) }) }) diff --git a/packages/client/ui-tool/tests/search-card.client.spec.tsx b/packages/client/ui-tool/tests/search-card.client.spec.tsx index ca8e8bde20..cee488b8b6 100644 --- a/packages/client/ui-tool/tests/search-card.client.spec.tsx +++ b/packages/client/ui-tool/tests/search-card.client.spec.tsx @@ -236,7 +236,7 @@ describe('SearchRow keyed card', () => { it('collapses to the summary row; expanding reveals the grep card', () => { const view = render() - expect(view.getByText('Grep')).toBeTruthy() + expect(view.getByText('搜索文件内容')).toBeTruthy() expect(view.queryByText('Search')).toBeNull() // Collapsed: the card is not in the DOM until the row is expanded. expect(searchKindOf(view.container)).toBeNull() @@ -250,7 +250,7 @@ describe('SearchRow keyed card', () => { it('expands to the glob path card', () => { const view = render() - expect(view.getByText('Glob')).toBeTruthy() + expect(view.getByText('查找文件')).toBeTruthy() expect(view.queryByText('Search')).toBeNull() expect(searchKindOf(view.container)).toBeNull() toggleRow(view) diff --git a/packages/client/ui-tool/tests/tool-row.client.spec.tsx b/packages/client/ui-tool/tests/tool-row.client.spec.tsx index 6ef6cd713a..d4749831be 100644 --- a/packages/client/ui-tool/tests/tool-row.client.spec.tsx +++ b/packages/client/ui-tool/tests/tool-row.client.spec.tsx @@ -81,10 +81,10 @@ describe('tool-call-model', () => { expect(t(toolRowModel('cordis_unmount', running({ name: 'cordis_unmount', argsRaw: '{}' })).titleKey)).toBe('工具调用') }) - it('gives the pwsh shell row the bash family treatment with its own title', () => { + it('gives the pwsh shell row the bash family treatment and localized command title', () => { const m = toolRowModel('pwsh', running()) expect(m.variant).toBe('bash') - expect(t(m.titleKey)).toBe('Pwsh') + expect(t(m.titleKey)).toBe('运行命令') }) it('derives state across running/ok/error/interrupted', () => { @@ -96,7 +96,7 @@ describe('tool-call-model', () => { it('derives the bash summary from description over command', () => { const m = toolRowModel('bash', running()) - expect(t(m.titleKey)).toBe('Bash') + expect(t(m.titleKey)).toBe('运行命令') expect(m.summary).toBe('List files') expect(toolRowModel('bash', running({ argsRaw: '{"command":"pwd"}' })).summary).toBe('pwd') }) @@ -420,7 +420,7 @@ describe('ToolRow', () => { it('an error row without an error summary keeps the args summary', () => { const view = render() const summary = view.getByText('List files') - expect(summary.className).toContain('errorSummary') + expect(summary.parentElement?.className).toContain('errorSummary') }) it('renders summarySuffix outside the ellipsized summary span, and drops it on a failure line', () => { @@ -499,7 +499,7 @@ describe('GenericToolCard', () => { it('renders the classified variant row from the frozen slice', () => { const view = render() - expect(view.getByText('Bash')).toBeTruthy() + expect(view.getByText('运行命令')).toBeTruthy() expect(view.getByText('List files')).toBeTruthy() expect(view.container.querySelector('[data-variant="bash"]')).not.toBeNull() }) @@ -556,7 +556,7 @@ describe('GenericToolCard', () => { it('passes the owner inspect callback through to the expanded row pill', () => { const inspect = vi.fn() const view = render() - fireEvent.click(view.getByRole('button', { name: /Bash/ })) + fireEvent.click(view.getByRole('button', { name: /运行命令/ })) fireEvent.click(view.getByText('查看')) expect(inspect).toHaveBeenCalledTimes(1) }) 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 e49ab33f28..73647081a7 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -176,7 +176,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.assistant-actions\', () => ctx.slots.register(\n { name: \'conversation.chat.assistant-actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:227', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:243', }, { key: 'conversation.chat.commandview', @@ -224,7 +224,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.commandview\', () => ctx.slots.register(\n { name: \'conversation.chat.commandview\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:215', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:231', }, { key: 'conversation.chat.node', @@ -293,7 +293,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.chat.node\', () => ctx.slots.register(\n { name: \'conversation.chat.node\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:196', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:212', }, { key: 'conversation.chat.turnTail', @@ -354,7 +354,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.turnTail\', () => ctx.slots.register(\n { name: \'conversation.chat.turnTail\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:221', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:237', }, { key: 'conversation.composer', @@ -1126,7 +1126,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.message.images\', () => ctx.slots.register(\n { name: \'conversation.message.images\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:209', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:225', }, { key: 'conversation.plan-review.actions', diff --git a/snapshots/web/bash-abort-row/ui.expected.md b/snapshots/web/bash-abort-row/ui.expected.md index d6188dfffa..911bf72973 100644 --- a/snapshots/web/bash-abort-row/ui.expected.md +++ b/snapshots/web/bash-abort-row/ui.expected.md @@ -5,7 +5,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: "Run two shell commands: wait for cancellation, then write skipped.txt. {{clock}}" - button "Copy" - button "Context injection runtime-context" diff --git a/snapshots/web/changed-files-turn/ui.expected.md b/snapshots/web/changed-files-turn/ui.expected.md index 197e8c92f5..f1942da607 100644 --- a/snapshots/web/changed-files-turn/ui.expected.md +++ b/snapshots/web/changed-files-turn/ui.expected.md @@ -1,14 +1,13 @@ -- button "系统提示词" - text: 不用先查看目录,直接做四件事:把 intro.md 里的标题「示例项目」改成「项目说明」,新建 src/util.ts 导出一个两数相加的 add 函数,新建 app.local 写一行 mode=demo,最后用 bash 在 notes.txt 末尾追加一行 done。 {{clock}} - button "复制" - button "7 次工具调用" [expanded] - button "上下文注入 runtime-context" -- button "思考 The user wants four things done directly. But I need to read intro.md before editing (fs-observation-policy requires reading existing file first). The user says don't look at the directory first, but reading intro.md is needed for the edit tool. Let me just do it." +- button "思考" - button "读取 intro.md": - text: 读取 - button "intro.md" -- button "Bash List files and show notes.txt" -- button "思考 Now do all four actions. Edit intro.md, write src/util.ts, write app.local, bash append." +- button "运行命令 List files and show notes.txt" +- button "思考" - button "编辑 intro.md +1 -1": - text: 编辑 - button "intro.md" @@ -21,8 +20,8 @@ - text: 写入 - button "app.local" - text: +1 -0 -- button "Bash Append done to notes.txt" -- 'button "思考 All four done. Present the files? The user asked to create files. I should call present for the deliverables. Files: intro.md, src/util.ts, app.local, notes.txt. All are outputs. Let me present them."' +- button "运行命令 Append done to notes.txt" +- button "思考" - button "交付文件 已交付 intro.md, src/util.ts, app.local, notes.txt" - paragraph: 四件事全部完成: - list: diff --git a/snapshots/web/deepseek-messages-chat/ui.expected.md b/snapshots/web/deepseek-messages-chat/ui.expected.md index 9a790ba8ea..9704a35af6 100644 --- a/snapshots/web/deepseek-messages-chat/ui.expected.md +++ b/snapshots/web/deepseek-messages-chat/ui.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "对话" [selected] - tab "轨迹" -- button "系统提示词" - text: 只回复 MESSAGES_WEB_READY,不调用工具。 {{clock}} - button "复制" - button "已思考" diff --git a/snapshots/web/default-workspace/ui.expected.md b/snapshots/web/default-workspace/ui.expected.md index 425343834b..7988d45c0c 100644 --- a/snapshots/web/default-workspace/ui.expected.md +++ b/snapshots/web/default-workspace/ui.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: "Use the bash tool to run exactly: echo WEB_E2E_OK. Then reply with the single word DONE and stop. {{clock}}" - button "Copy" - button "1 tool call" diff --git a/snapshots/web/feedback-command/ack-expanded.expected.md b/snapshots/web/feedback-command/ack-expanded.expected.md index 50bc047607..d9c09956cf 100644 --- a/snapshots/web/feedback-command/ack-expanded.expected.md +++ b/snapshots/web/feedback-command/ack-expanded.expected.md @@ -6,12 +6,11 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Reply with the single word LIGHTHOUSE and stop. {{clock}} - button "Copy" - button "Thought for a while" [expanded] - button "Context injection runtime-context" -- button "Think The user wants me to reply with a single word. Let me comply." +- button "Think" - paragraph: LIGHTHOUSE - button "Copy" - button "Good response" diff --git a/snapshots/web/feedback-command/ack.expected.md b/snapshots/web/feedback-command/ack.expected.md index d553156708..b5060084a4 100644 --- a/snapshots/web/feedback-command/ack.expected.md +++ b/snapshots/web/feedback-command/ack.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Reply with the single word LIGHTHOUSE and stop. {{clock}} - button "Copy" - button "Thought for a while" diff --git a/snapshots/web/feedback-release/ack-expanded.expected.md b/snapshots/web/feedback-release/ack-expanded.expected.md index 50bc047607..d9c09956cf 100644 --- a/snapshots/web/feedback-release/ack-expanded.expected.md +++ b/snapshots/web/feedback-release/ack-expanded.expected.md @@ -6,12 +6,11 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Reply with the single word LIGHTHOUSE and stop. {{clock}} - button "Copy" - button "Thought for a while" [expanded] - button "Context injection runtime-context" -- button "Think The user wants me to reply with a single word. Let me comply." +- button "Think" - paragraph: LIGHTHOUSE - button "Copy" - button "Good response" diff --git a/snapshots/web/feedback-release/ack.expected.md b/snapshots/web/feedback-release/ack.expected.md index d553156708..b5060084a4 100644 --- a/snapshots/web/feedback-release/ack.expected.md +++ b/snapshots/web/feedback-release/ack.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Reply with the single word LIGHTHOUSE and stop. {{clock}} - button "Copy" - button "Thought for a while" diff --git a/snapshots/web/file-upload-round/ui.expected.md b/snapshots/web/file-upload-round/ui.expected.md index 6435e7d5bf..fc6a0cf362 100644 --- a/snapshots/web/file-upload-round/ui.expected.md +++ b/snapshots/web/file-upload-round/ui.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: poem.txt TXT 16B - button "reference-1.png, click to view original": - img "reference-1.png" diff --git a/snapshots/web/fresh-round-trip/ui-expanded.expected.md b/snapshots/web/fresh-round-trip/ui-expanded.expected.md index 0b593347b8..1bbd83f0d9 100644 --- a/snapshots/web/fresh-round-trip/ui-expanded.expected.md +++ b/snapshots/web/fresh-round-trip/ui-expanded.expected.md @@ -6,14 +6,13 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: "Use the bash tool to run exactly: echo WEB_E2E_OK. Then reply with the single word DONE and stop. {{clock}}" - button "Copy" - button "1 tool call" [expanded] - button "Context injection runtime-context" -- button "Think The user wants me to run a simple bash command and reply with \"DONE\"." +- button "Think" - button "Bash Echo the test string" -- button "Think The command executed successfully and output \"WEB_E2E_OK\". I just need to reply with \"DONE\"." +- button "Think" - paragraph: DONE - button "Copy" - button "Good response" diff --git a/snapshots/web/fresh-round-trip/ui.expected.md b/snapshots/web/fresh-round-trip/ui.expected.md index 425343834b..7988d45c0c 100644 --- a/snapshots/web/fresh-round-trip/ui.expected.md +++ b/snapshots/web/fresh-round-trip/ui.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: "Use the bash tool to run exactly: echo WEB_E2E_OK. Then reply with the single word DONE and stop. {{clock}}" - button "Copy" - button "1 tool call" 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 ffd5ea6805..7c9f533f8c 100644 --- a/snapshots/web/goal-multi-turn-actions/ui-expanded.expected.md +++ b/snapshots/web/goal-multi-turn-actions/ui-expanded.expected.md @@ -11,22 +11,21 @@ - button "Jump to turn 2" - group "Command input": /goal 做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的 - 'button "goal Goal created Status: active Objective: 做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的 Rounds: 0/256 Activation: armed Commands: /goal edit , /goal pause, /goal clear"' -- button "System prompt" - button "6 tool calls" [expanded] - button "Context injection goal" - button "Context injection runtime-context" -- 'button "Think The user''s goal is: \"做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的\" — which translates to: \"Do two turns, each turn output the file structure of a random package. Note that after you finish one turn, directly output the content and stop; our system will help you open another turn, and you just do something similar.\""' +- button "Think" - button "Bash List package directories deterministically" - button "View goal 做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的" -- 'button "Think There''s a `packages` directory. Let me look inside to see what packages are available."' +- button "Think" - button "Bash List packages directory contents" -- button "Think There are 4 packages:" +- button "Think" - button "Failed Bash Randomly pick one package directory" -- 'button "Think shuf is not available on macOS. I''ll use a different approach for random selection. Let me use $RANDOM in bash or use `sort -R` or Python."' +- button "Think" - button "Bash Randomly select one package with Python" -- 'button "Think The random pick for turn 1 is `packages/context/session-reference`. Now I''ll output its file structure. Let me get the file tree."' +- button "Think" - button "Bash List all files in session-reference package" -- 'button "Think Turn 1 is done. Per the objective: \"你做完一个turn之后,直接输出内容,停止\" — after finishing a turn, directly output the content and stop. The system will open another turn."' +- button "Think" - paragraph: - strong: Turn 1 / 2 - text: — 随机选中的包: @@ -42,15 +41,14 @@ - button "Bad response" - button "Branch into a new conversation" - text: {{clock}} -- button "System prompt" - button "5 tool calls · 2 messages" [expanded] - button "Context injection goal" -- 'button "Think This is turn 2 of 2. I need to randomly pick another package and output its file structure. In the first turn I picked `packages/context/session-reference`. Let me pick a different one randomly this time."' +- button "Think" - button "Bash Randomly select another package with Python" -- 'button "Think The random pick returned the same package as turn 1. Since turn 1 already covered `session-reference`, it would be better to pick a different one for variety. Let me re-roll, excluding the already-covered package."' +- button "Think" - button "Bash Re-roll excluding the package from turn 1" - button "Bash List all files in token-meter package" -- 'button "Think This is turn 2 of 2. I''ve output the file structure for `packages/llm/token-meter`. Both turns are done. I should output the content, stop, and then mark the goal as complete since both turns are finished."' +- button "Think" - paragraph: - strong: Turn 2 / 2 - text: — 随机选中的包: diff --git a/snapshots/web/goal-multi-turn-actions/ui.expected.md b/snapshots/web/goal-multi-turn-actions/ui.expected.md index 59dc395da6..2d7d6a5d24 100644 --- a/snapshots/web/goal-multi-turn-actions/ui.expected.md +++ b/snapshots/web/goal-multi-turn-actions/ui.expected.md @@ -11,7 +11,6 @@ - button "Jump to turn 2" - group "Command input": /goal 做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的 - 'button "goal Goal created Status: active Objective: 做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的 Rounds: 0/256 Activation: armed Commands: /goal edit , /goal pause, /goal clear"' -- button "System prompt" - button "6 tool calls" - paragraph: - strong: Turn 1 / 2 @@ -28,7 +27,6 @@ - button "Bad response" - button "Branch into a new conversation" - text: {{clock}} -- button "System prompt" - button "5 tool calls · 2 messages" - paragraph: 两个 turn 都完成了 ✅ - paragraph: diff --git a/snapshots/web/lifecycle-chrome/reloaded-expanded.expected.md b/snapshots/web/lifecycle-chrome/reloaded-expanded.expected.md index 8e1c4db5cc..8b6f7eae5f 100644 --- a/snapshots/web/lifecycle-chrome/reloaded-expanded.expected.md +++ b/snapshots/web/lifecycle-chrome/reloaded-expanded.expected.md @@ -6,12 +6,11 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Reply with the single word LIGHTHOUSE and stop. {{clock}} - button "Copy" - button "Thought for a while" [expanded] - button "Context injection runtime-context" -- button "Think The user wants me to reply with a single word. Let me comply." +- button "Think" - paragraph: LIGHTHOUSE - button "Copy" - button "Good response" diff --git a/snapshots/web/lifecycle-chrome/reloaded.expected.md b/snapshots/web/lifecycle-chrome/reloaded.expected.md index c4bf010378..a760c82371 100644 --- a/snapshots/web/lifecycle-chrome/reloaded.expected.md +++ b/snapshots/web/lifecycle-chrome/reloaded.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Reply with the single word LIGHTHOUSE and stop. {{clock}} - button "Copy" - button "Thought for a while" diff --git a/snapshots/web/live-interactions/cancel-expanded.expected.md b/snapshots/web/live-interactions/cancel-expanded.expected.md index 1cbe13209e..3813c500b7 100644 --- a/snapshots/web/live-interactions/cancel-expanded.expected.md +++ b/snapshots/web/live-interactions/cancel-expanded.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy" - button "Thought for a while" [expanded] diff --git a/snapshots/web/live-interactions/cancel.expected.md b/snapshots/web/live-interactions/cancel.expected.md index b30b140798..8b64580291 100644 --- a/snapshots/web/live-interactions/cancel.expected.md +++ b/snapshots/web/live-interactions/cancel.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy" - button "Thought for a while" diff --git a/snapshots/web/live-interactions/error-auth.expected.md b/snapshots/web/live-interactions/error-auth.expected.md index aa423c09dc..4a5dd961fe 100644 --- a/snapshots/web/live-interactions/error-auth.expected.md +++ b/snapshots/web/live-interactions/error-auth.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy" - button "Context injection runtime-context" diff --git a/snapshots/web/live-interactions/loading.expected.md b/snapshots/web/live-interactions/loading.expected.md index 67b4bf71a4..4635768121 100644 --- a/snapshots/web/live-interactions/loading.expected.md +++ b/snapshots/web/live-interactions/loading.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy" - button "Context injection runtime-context" diff --git a/snapshots/web/live-interactions/retry-exhausted.expected.md b/snapshots/web/live-interactions/retry-exhausted.expected.md index 0f9f0503c1..2433cb613f 100644 --- a/snapshots/web/live-interactions/retry-exhausted.expected.md +++ b/snapshots/web/live-interactions/retry-exhausted.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy" - button "Context injection runtime-context" diff --git a/snapshots/web/live-interactions/retry-expanded.expected.md b/snapshots/web/live-interactions/retry-expanded.expected.md index d201eba408..5ea5441f23 100644 --- a/snapshots/web/live-interactions/retry-expanded.expected.md +++ b/snapshots/web/live-interactions/retry-expanded.expected.md @@ -6,14 +6,13 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy" - button "Thought for a while" [expanded] - button "Context injection runtime-context" - group: - status: Retried model request (1/5) · {{duration}} -- button "Think The user is asking for a one-sentence description of event sourcing. This is a straightforward knowledge question that doesn't require any skill loading or tool calls." +- button "Think" - paragraph: Event sourcing is a pattern where all changes to an application's state are stored as an immutable, append-only sequence of events, rather than persisting only the current state, enabling full auditability, temporal queries, and event-driven architectures. - button "Copy" - button "Good response" diff --git a/snapshots/web/live-interactions/retry.expected.md b/snapshots/web/live-interactions/retry.expected.md index 435a2aac62..a122990338 100644 --- a/snapshots/web/live-interactions/retry.expected.md +++ b/snapshots/web/live-interactions/retry.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy" - button "Thought for a while" diff --git a/snapshots/web/live-interactions/running-draft.expected.md b/snapshots/web/live-interactions/running-draft.expected.md index 6518e42770..92ddaed171 100644 --- a/snapshots/web/live-interactions/running-draft.expected.md +++ b/snapshots/web/live-interactions/running-draft.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy" - button "Context injection runtime-context" diff --git a/snapshots/web/message-actions/ui.expected.md b/snapshots/web/message-actions/ui.expected.md index df127b9b31..f4776040f5 100644 --- a/snapshots/web/message-actions/ui.expected.md +++ b/snapshots/web/message-actions/ui.expected.md @@ -9,11 +9,10 @@ - button "Jump to turn 1" - button "Jump to turn 2" - button "Jump to turn 3" -- button "System prompt" - text: "Use the read tool twice in one assistant message: read a.txt and b.txt. Then reply with the single word DONE and stop. {{clock}}" - button "Copy" - tooltip "Copy" -- button "Think The user wants me to read a.txt and b.txt, then reply with \"DONE\". Let me do both reads in parallel." +- button "Think" - paragraph: I will read both files before answering. - button "Copy" - button "Good response" @@ -26,7 +25,6 @@ - button "Read b.txt": - text: Read - button "b.txt" -- button "System prompt" - text: Now give the final answer. {{clock}} - button "Copy" - paragraph: DONE diff --git a/snapshots/web/minimal-preset/ui.expected.md b/snapshots/web/minimal-preset/ui.expected.md index 3567494649..e7e695c43c 100644 --- a/snapshots/web/minimal-preset/ui.expected.md +++ b/snapshots/web/minimal-preset/ui.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: "Use the bash tool to run exactly: printf 'MINIMAL_BASH_CARD_OK\\n'. Then reply exactly MINIMAL_PRESET_REQUEST_OK and stop. {{clock}}" - button "Copy" - button "1 tool call" [expanded] diff --git a/snapshots/web/plan-review/approved-expanded.expected.md b/snapshots/web/plan-review/approved-expanded.expected.md index 71a77be2f5..602b7120f8 100644 --- a/snapshots/web/plan-review/approved-expanded.expected.md +++ b/snapshots/web/plan-review/approved-expanded.expected.md @@ -5,20 +5,17 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- text: plan Plan mode on. Use /plan off to leave. -- button "System prompt" -- text: "Plan a small change: add a --greeting flag to a CLI. Do not read or write any files. Call exit_plan_mode with a short plan of at most five bullet points. Once the plan is approved, reply with the single word DONE and stop. {{clock}}" +- text: "plan Plan mode on. Use /plan off to leave. Plan a small change: add a --greeting flag to a CLI. Do not read or write any files. Call exit_plan_mode with a short plan of at most five bullet points. Once the plan is approved, reply with the single word DONE and stop. {{clock}}" - button "Copy" - button "1 tool call · 1 message" [expanded] - button "Context injection runtime-context" -- 'button "Think The user wants me to plan a small change to add a `--greeting` flag to a CLI. They explicitly told me not to read or write any files, and to call exit_plan_mode with a short plan. Let me do that directly."' +- button "Think" - paragraph: - text: Since the user has explicitly asked me not to read or write any files and to go straight to planning, I'll proceed with - code: exit_plan_mode - text: . - 'button "Tool call exit_plan_mode · # Add `--greeting` flag to CLI"' -- button "System prompt" -- 'button "Think The plan was approved. The user''s last instruction says: \"Once the plan is approved, reply with the single word DONE and stop.\" So I should just reply with DONE and stop."' +- button "Think" - paragraph: DONE - 'button "Open plan: Add `--greeting` flag to CLI"': "Add `--greeting` flag to CLI Plan · Markdown Open" - button "Copy" diff --git a/snapshots/web/plan-review/approved.expected.md b/snapshots/web/plan-review/approved.expected.md index 94ba2c08b5..fe52ec9268 100644 --- a/snapshots/web/plan-review/approved.expected.md +++ b/snapshots/web/plan-review/approved.expected.md @@ -5,12 +5,9 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- text: plan Plan mode on. Use /plan off to leave. -- button "System prompt" -- text: "Plan a small change: add a --greeting flag to a CLI. Do not read or write any files. Call exit_plan_mode with a short plan of at most five bullet points. Once the plan is approved, reply with the single word DONE and stop. {{clock}}" +- text: "plan Plan mode on. Use /plan off to leave. Plan a small change: add a --greeting flag to a CLI. Do not read or write any files. Call exit_plan_mode with a short plan of at most five bullet points. Once the plan is approved, reply with the single word DONE and stop. {{clock}}" - button "Copy" - button "1 tool call · 1 message" -- button "System prompt" - paragraph: DONE - 'button "Open plan: Add `--greeting` flag to CLI"': "Add `--greeting` flag to CLI Plan · Markdown Open" - button "Copy" diff --git a/snapshots/web/present-svg/ui.expected.md b/snapshots/web/present-svg/ui.expected.md index c867d85c45..5238b2a252 100644 --- a/snapshots/web/present-svg/ui.expected.md +++ b/snapshots/web/present-svg/ui.expected.md @@ -1,15 +1,14 @@ -- button "系统提示词" - text: 简单画一个 SVG 表示冯诺依曼架构, 保存为 von-neumann.svg {{clock}} - button "复制" - button "2 次工具调用 · 1 条消息" [expanded] - button "上下文注入 runtime-context" -- button "思考 The user wants a simple SVG diagram of the von Neumann architecture, saved as von-neumann.svg. Let me create a clean SVG showing CPU (control unit, ALU), memory, input, and output with bidirectional data/control buses." +- button "思考" - paragraph: 我来创建一个冯诺依曼架构的 SVG 示意图。 - button "写入 von-neumann.svg +83 -0": - text: 写入 - button "von-neumann.svg" - text: +83 -0 -- button "思考 The file is created. Let me present it as a deliverable." +- button "思考" - button "交付文件 已交付 von-neumann.svg" - paragraph: - text: 已创建 diff --git a/snapshots/web/present/ui.expected.md b/snapshots/web/present/ui.expected.md index ad3780520c..02fb01a3f8 100644 --- a/snapshots/web/present/ui.expected.md +++ b/snapshots/web/present/ui.expected.md @@ -6,18 +6,17 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: "Use one run_code program to do the following in order. Call present for missing.txt and catch its error without creating that file. Use bash to run exactly `printf \"DELIVERED_REPORT\\n\" > report.txt; printf \"DELIVERED_NOTE\\n\" > 说明.txt`. Call present for report.txt and 说明.txt. After present succeeds, deliberately throw the string \"AFTER_PRESENT\" (not an Error object) from that same run_code program. Do not retry the program or create any other files. Finish by mentioning `report.txt` and `说明.txt` in inline code, and put PRESENT_DONE in a separate paragraph. {{clock}}" - button "Copy" - button "1 tool call" [expanded] - button "Context injection runtime-context" -- button "Think The user wants one run_code program that:" +- button "Think" - text: Failed - 'button "Code Error: code run failed (exception): AFTER_PRESENT"' - button "Present files Delivery failed missing.txt" - button "Bash Write DELIVERED_REPORT and DELIVERED_NOTE to files" - button "Present files Delivered report.txt, 说明.txt" -- button "Think The program ran as intended:" +- button "Think" - paragraph: - text: "The single program ran exactly as ordered:" - code: present diff --git a/snapshots/web/ptc-round/ui.expected.md b/snapshots/web/ptc-round/ui.expected.md index c62860982b..9e68c8604a 100644 --- a/snapshots/web/ptc-round/ui.expected.md +++ b/snapshots/web/ptc-round/ui.expected.md @@ -6,12 +6,11 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: "Using ONE run_code program: run bash `echo CODE_ROUND_OK`, then read the file missing.txt catching its error in the program. Return an object with both outcomes. Then reply DONE and stop. {{clock}}" - button "Copy" - button "1 tool call" [expanded] - button "Context injection runtime-context" -- 'button "Think The user wants me to write a single `run_code` program that:"' +- button "Think" - button "Code Run bash echo and catch missing file read" - button "Bash Echo CODE_ROUND_OK" [expanded] - text: Done workspace echo CODE_ROUND_OK @@ -20,7 +19,7 @@ - button "Inspect" - text: Failed - 'button "Read Error: cannot read \"{{cwd}}/workspace/missing.txt\": not found"' -- button "Think The program ran successfully. Let me now reply DONE as instructed." +- button "Think" - paragraph: DONE - button "Copy" - button "Good response" diff --git a/snapshots/web/question-composer/answered-expanded.expected.md b/snapshots/web/question-composer/answered-expanded.expected.md index 1e5e5a39cb..488e8b8029 100644 --- a/snapshots/web/question-composer/answered-expanded.expected.md +++ b/snapshots/web/question-composer/answered-expanded.expected.md @@ -6,17 +6,16 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: "Use the ask_user_question tool to ask me exactly one multi-select question with id \"color\", question \"Which color do you prefer?\", header \"Pick one\", and two options: label \"Blue\" with description \"A cool recessive hue that reads as calm and trustworthy in long reading sessions and dense dashboards.\", and label \"Green\" with description \"A restful mid-spectrum hue with the highest perceived brightness, easiest on the eye over long sessions.\" Set multi_select to true. After I answer, reply with the single word DONE and stop. {{clock}}" - button "Copy" - button "1 tool call" [expanded] - button "Context injection runtime-context" -- button "Think The user wants me to use the ask_user_question tool with specific parameters. Let me do exactly that." +- button "Think" - button "Ask question 1/1 answered" [expanded] - term: Which color do you prefer? - definition: Blue Include accessibility notes - button "Inspect" -- button "Think The user answered \"Blue\". I should now reply with the single word DONE and stop." +- button "Think" - paragraph: DONE - button "Copy" - button "Good response" diff --git a/snapshots/web/question-composer/answered.expected.md b/snapshots/web/question-composer/answered.expected.md index dd494fb614..fa8b822467 100644 --- a/snapshots/web/question-composer/answered.expected.md +++ b/snapshots/web/question-composer/answered.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: "Use the ask_user_question tool to ask me exactly one multi-select question with id \"color\", question \"Which color do you prefer?\", header \"Pick one\", and two options: label \"Blue\" with description \"A cool recessive hue that reads as calm and trustworthy in long reading sessions and dense dashboards.\", and label \"Green\" with description \"A restful mid-spectrum hue with the highest perceived brightness, easiest on the eye over long sessions.\" Set multi_select to true. After I answer, reply with the single word DONE and stop. {{clock}}" - button "Copy" - button "1 tool call" diff --git a/snapshots/web/question-composer/cancelled.expected.md b/snapshots/web/question-composer/cancelled.expected.md index 15af0b5cc7..7238215d90 100644 --- a/snapshots/web/question-composer/cancelled.expected.md +++ b/snapshots/web/question-composer/cancelled.expected.md @@ -5,11 +5,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: "Use the ask_user_question tool to ask me exactly one multi-select question with id \"color\", question \"Which color do you prefer?\", header \"Pick one\", and two options: label \"Blue\" with description \"A cool recessive hue that reads as calm and trustworthy in long reading sessions and dense dashboards.\", and label \"Green\" with description \"A restful mid-spectrum hue with the highest perceived brightness, easiest on the eye over long sessions.\" Set multi_select to true. After I answer, reply with the single word DONE and stop. {{clock}}" - button "Copy" - button "Context injection runtime-context" -- button "Think The user wants me to use the ask_user_question tool with specific parameters. Let me do exactly that." +- button "Think" - button "Ask question cancelled" [expanded] - paragraph: This question set was cancelled before answers were submitted. - list: diff --git a/snapshots/web/queue-actions/collapsed.expected.md b/snapshots/web/queue-actions/collapsed.expected.md index 765e045f17..bcb7ecf753 100644 --- a/snapshots/web/queue-actions/collapsed.expected.md +++ b/snapshots/web/queue-actions/collapsed.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy" - button "Context injection runtime-context" diff --git a/snapshots/web/queue-actions/editing.expected.md b/snapshots/web/queue-actions/editing.expected.md index 96eff6022d..13925614bf 100644 --- a/snapshots/web/queue-actions/editing.expected.md +++ b/snapshots/web/queue-actions/editing.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy" - button "Context injection runtime-context" diff --git a/snapshots/web/queue-actions/layout.expected.md b/snapshots/web/queue-actions/layout.expected.md index 0d5d2ce2b1..4ca4469eed 100644 --- a/snapshots/web/queue-actions/layout.expected.md +++ b/snapshots/web/queue-actions/layout.expected.md @@ -8,7 +8,6 @@ - tab "Trajectory" - group "Command input": /goal Keep the composer context panels aligned - 'button "goal Goal created Status: active Objective: Keep the composer context panels aligned Rounds: 0/256 Activation: armed Commands: /goal edit , /goal pause, /goal clear"' -- button "System prompt" - button "Context injection goal" - button "Context injection runtime-context" - paragraph: partial diff --git a/snapshots/web/queue-actions/preserved-expanded.expected.md b/snapshots/web/queue-actions/preserved-expanded.expected.md index fe66236496..e95a3f6fb3 100644 --- a/snapshots/web/queue-actions/preserved-expanded.expected.md +++ b/snapshots/web/queue-actions/preserved-expanded.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy" - button "Thought for a while" [expanded] diff --git a/snapshots/web/queue-actions/preserved.expected.md b/snapshots/web/queue-actions/preserved.expected.md index 66052f1522..3f186da354 100644 --- a/snapshots/web/queue-actions/preserved.expected.md +++ b/snapshots/web/queue-actions/preserved.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy" - button "Thought for a while" diff --git a/snapshots/web/queue-actions/sending.expected.md b/snapshots/web/queue-actions/sending.expected.md index 07dd357aba..02e60e5f77 100644 --- a/snapshots/web/queue-actions/sending.expected.md +++ b/snapshots/web/queue-actions/sending.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy" - button "Context injection runtime-context" diff --git a/snapshots/web/queue-actions/ui.expected.md b/snapshots/web/queue-actions/ui.expected.md index 9e43a41140..fcc1477d43 100644 --- a/snapshots/web/queue-actions/ui.expected.md +++ b/snapshots/web/queue-actions/ui.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy" - button "Context injection runtime-context" diff --git a/snapshots/web/queued-image/delivered.expected.md b/snapshots/web/queued-image/delivered.expected.md index 289963776b..a77a5d3547 100644 --- a/snapshots/web/queued-image/delivered.expected.md +++ b/snapshots/web/queued-image/delivered.expected.md @@ -10,7 +10,6 @@ - button "Jump to turn 1" - button "Jump to turn 2" - button "Jump to turn 3" -- button "System prompt" - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy" - button "Thought for a while" diff --git a/snapshots/web/queued-image/queued.expected.md b/snapshots/web/queued-image/queued.expected.md index e28d8df980..95b98d26cd 100644 --- a/snapshots/web/queued-image/queued.expected.md +++ b/snapshots/web/queued-image/queued.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy" - button "Context injection runtime-context" diff --git a/snapshots/web/seeded-history/command-row.expected.md b/snapshots/web/seeded-history/command-row.expected.md index 727368f383..bcebaccbe0 100644 --- a/snapshots/web/seeded-history/command-row.expected.md +++ b/snapshots/web/seeded-history/command-row.expected.md @@ -8,18 +8,17 @@ - navigation "Turn navigation": - button "Jump to turn 1" - button "Jump to turn 2" -- button "System prompt" - text: "Use the read tool twice in one assistant message: read a.txt and b.txt. Then reply with the single word DONE and stop. {{clock}}" - button "Copy" - button "2 tool calls" [expanded] -- button "Think The user wants me to read a.txt and b.txt, then reply with \"DONE\". Let me do both reads in parallel." +- button "Think" - button "Read a.txt": - text: Read - button "a.txt" - button "Read b.txt": - text: Read - button "b.txt" -- button "Think Both files have been read. a.txt contains \"alpha\" and b.txt contains \"beta\". I'll now reply with DONE as instructed." +- button "Think" - paragraph: DONE - button "Copy" - button "Good response" @@ -28,7 +27,6 @@ - text: {{clock}} - button "compact Compacted 5 history items (~{{tokens}} tokens)" - button "Context injection AGENTS.md" -- text: permission preset read-only - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" - 'button "Access mode, current: Read Only"': Read Only diff --git a/snapshots/web/seeded-history/feedback-row.expected.md b/snapshots/web/seeded-history/feedback-row.expected.md index 2b26bde0d6..cb0bde06e7 100644 --- a/snapshots/web/seeded-history/feedback-row.expected.md +++ b/snapshots/web/seeded-history/feedback-row.expected.md @@ -8,18 +8,17 @@ - navigation "Turn navigation": - button "Jump to turn 1" - button "Jump to turn 2" -- button "System prompt" - text: "Use the read tool twice in one assistant message: read a.txt and b.txt. Then reply with the single word DONE and stop. {{clock}}" - button "Copy" - button "2 tool calls" [expanded] -- button "Think The user wants me to read a.txt and b.txt, then reply with \"DONE\". Let me do both reads in parallel." +- button "Think" - button "Read a.txt": - text: Read - button "a.txt" - button "Read b.txt": - text: Read - button "b.txt" -- button "Think Both files have been read. a.txt contains \"alpha\" and b.txt contains \"beta\". I'll now reply with DONE as instructed." +- button "Think" - paragraph: DONE - button "Copy" - button "Good response" @@ -28,7 +27,6 @@ - text: {{clock}} - button "compact Compacted 5 history items (~{{tokens}} tokens)" - button "Context injection AGENTS.md" -- text: permission preset read-only - 'button "feedback Feedback recorded for session {{seededId}} Anonymous user: {{uuid}}." [expanded]' - text: "Feedback recorded for session {{seededId}} Anonymous user: {{uuid}}." - textbox "Message or run a task, / commands, @ files or sessions" diff --git a/snapshots/web/seeded-history/ui-expanded.expected.md b/snapshots/web/seeded-history/ui-expanded.expected.md index bd687552fd..4f6ac15000 100644 --- a/snapshots/web/seeded-history/ui-expanded.expected.md +++ b/snapshots/web/seeded-history/ui-expanded.expected.md @@ -8,18 +8,17 @@ - navigation "Turn navigation": - button "Jump to turn 1" - button "Jump to turn 2" -- button "System prompt" - text: "Use the read tool twice in one assistant message: read a.txt and b.txt. Then reply with the single word DONE and stop. {{clock}}" - button "Copy" - button "2 tool calls" [expanded] -- button "Think The user wants me to read a.txt and b.txt, then reply with \"DONE\". Let me do both reads in parallel." +- button "Think" - button "Read a.txt": - text: Read - button "a.txt" - button "Read b.txt": - text: Read - button "b.txt" -- button "Think Both files have been read. a.txt contains \"alpha\" and b.txt contains \"beta\". I'll now reply with DONE as instructed." +- button "Think" - paragraph: DONE - button "Copy" - button "Good response" diff --git a/snapshots/web/seeded-history/ui.expected.md b/snapshots/web/seeded-history/ui.expected.md index 0a26ac4c88..4f703e11d9 100644 --- a/snapshots/web/seeded-history/ui.expected.md +++ b/snapshots/web/seeded-history/ui.expected.md @@ -8,7 +8,6 @@ - navigation "Turn navigation": - button "Jump to turn 1" - button "Jump to turn 2" -- button "System prompt" - text: "Use the read tool twice in one assistant message: read a.txt and b.txt. Then reply with the single word DONE and stop. {{clock}}" - button "Copy" - button "2 tool calls" diff --git a/snapshots/web/skill-tool-row/ui.expected.md b/snapshots/web/skill-tool-row/ui.expected.md index aa014bd9e0..816b680d6e 100644 --- a/snapshots/web/skill-tool-row/ui.expected.md +++ b/snapshots/web/skill-tool-row/ui.expected.md @@ -5,17 +5,16 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Load the editing-cordis-compositions skill with the skill tool, then reply DONE. {{date}} {{clock}} - button "Copy" - button "1 tool call" [expanded] - button "Context injection runtime-context" - button "Context injection skill-catalog" -- button "Think Load the requested skill." +- button "Think" - button "Skill editing-cordis-compositions" [expanded] - region "Instructions": "Instructions Base directory for this skill: {{cwd}}/.dsh/skills/editing-cordis-compositions Resolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed. # Editing Cordis compositions Every capability in this harness is a plugin row in a `cordis.yml`. There is no separate configuration language: changing what an agent can do means changing which rows are composed for it. ## Off-limits **Never edit, delete, or overwrite a preset that ships with the deployment** — the `agent-presets` directory beside the deployment's own config, which supplies `standard`, `ptc`, `minimal`, and `cordis`. Never escalate the sandbox to reach it, even when a change there looks quicker. An upgrade overwrites that install, and corrupting `cordis` disables preset authoring itself. Reading a shipped composition is the intended way to start; writing to one is not, and neither is editing the host composition to work around a preset limitation. To change what a shipped preset does, copy it and edit the copy. Locally authored presets under the user root are yours to create, edit, and delete. ## Decide the plane first Two planes, and the choice is not about how \"agent-related\" something feels — it is about whether the thing must be shared. **Host composition.** The registries themselves (`tools`, `systemPrompt`, `agents`, `agent-loop`, `sessions`), anything crossing sessions (persistence, session query, storage, settings, credentials, telemetry), the sandbox and approval stack, the model route, and the subagent registry with its spawn/fork backends. One instance for the process. **Agent preset.** What one session contributes to those registries: its tool plugins, its persona and prompt sections, its compaction policy. One instance per session, mounted under that session's scope and unwound with it. **A service with a consumer outside the agent plane cannot move into a preset.** `subagents` is the worked example: the registry answers cross-session queries for the host api-proxy, so a per-session copy both starves that host row — it waits forever for a service nothing provides — and collides on the second session, since a provider name registers once. The preset contributes the delegation *tools*; the registry and its backends stay host-side. A preset is a directory holding one `agent.cordis.yml`, optionally beside a `preset.yml` carrying display metadata — `name` and `description` (and, for shipped presets, a roster `order`). Write the metadata too: a preset without it shows up in every picker as its bare directory name. Locally authored presets live one directory per preset under `${DSH_HOME:-$HOME/.dsh}/.agent-presets/`, and the shipped set sits beside the deployment's own config. Use those when the user asks where to look. For deployment overrides, read `${DSH_HOME:-$HOME/.dsh}/profiles//cordis.patch.yml`, `${DSH_HOME:-$HOME/.dsh}/cordis.patch.yml`, and any launch `--patch` files for the `agent-presets` row's `roots` and `includeUserRoot`. Obtain the active profile and extra patch paths from the user when they are not in the task context; do not guess a different profile. ## Authoring a preset Use shell and file tools to locate the installed `@deepseek-ai/dsh-agent-presets` package under the active profile's `node_modules` or the deployment installation. Its `presets//` directory contains each shipped preset. If those files are unavailable, ask the user to copy the preset through the Web preset picker and provide the copied directory; runtime API inspection does not execute Remote methods. Copy the complete source directory, including skills and assets, into a new `${DSH_HOME:-$HOME/.dsh}/.agent-presets//` directory (or the explicitly configured writable root). Refuse an existing destination. Set `name` and `description` in `preset.yml` and remove the copied roster `order`. Never overwrite the installed source. Edit the copy's `agent.cordis.yml` with the normal file tools. Writes outside the workspace follow the active filesystem approval policy. For profile-wide capabilities, author a workspace bundle and install it with `plugin_manager`; load `cordis-plugin-development` for packaging guidance. ## Service isolation A preset row that publishes a service needs an `isolate` realm containing both the provider and all its consumers. A tool that only consumes a host service remains outside that realm. Copy the shipped preset's existing groups rather than introducing service instances into the process-global realm. ```yaml - id: delegation name: cordis:group group: true isolate: workflowEngine: true config: - id: workflow-ptc name: '@deepseek-ai/dsh-workflow-ptc' config: provider: spawn - id: tool-workflow name: '@deepseek-ai/dsh-tool-workflow' ``` ## Verify a preset Check the edited YAML and referenced local files with file tools. Ask the user to select the new preset in the Web picker and start a session; this authoring agent cannot invoke the preset Remote API or start a Web session through inspection. Once the user provides a running session or browser control, inspect the visible tools and any activation diagnostic. File validation alone does not verify imports, service dependencies, or isolation. Report which checks ran and leave activation unverified until that session check succeeds. ## Native product subagents Codex and Claude Code providers are independent optional Profile Bundles. Install only the products a Profile needs, then restart the Profile so its Host registers those providers: ```sh dsh plugin --profile add @deepseek-ai/dsh-subagent-codex dsh plugin --profile add @deepseek-ai/dsh-subagent-claude-code dsh plugin --profile remove @deepseek-ai/dsh-subagent-codex dsh plugin --profile remove @deepseek-ai/dsh-subagent-claude-code ``` Each Bundle owns its Host availability; the preset separately grants one Agent its ordinary delegation tool. Never move a product provider into the preset and never add a product-specific settings field. Removing one package withdraws only that provider on the next Profile start. Copy these disabled templates from a shipped full preset and remove `disabled` only for the products the user requested: ```yaml - id: tool-subagent-codex name: '@deepseek-ai/dsh-tool-subagent' disabled: true config: provider: codex toolName: subagent_codex backgroundMode: one-shot maxDepth: provider-managed - id: tool-subagent-claude-code name: '@deepseek-ai/dsh-tool-subagent' disabled: true config: provider: claude-code toolName: subagent_claude_code backgroundMode: one-shot maxDepth: provider-managed ``` For additional named Codex or Claude Code instances, mount a separate host-plane provider row for each instance with a unique `providerName`, then add a separate preset tool row whose `provider` exactly matches that name and whose `toolName` is also unique. Keep the shipped rows for the default `codex` and `claude-code` names; do not reuse one tool row for several providers or derive either name from permission or environment settings. The two rows are independent. Leaving both disabled preserves the copied preset, enabling one exposes only that product tool, and enabling both exposes both. Production `dsh` does not install either optional provider: before enabling a row, install the matching `@deepseek-ai/dsh-subagent-codex` or `@deepseek-ai/dsh-subagent-claude-code` Bundle in the Profile and restart it. Each Bundle registers its dormant default provider and exclusively uses its pinned package-local platform CLI; additional named instances use extra host-plane rows from the same installed package. A preset cannot provide that host dependency. `backgroundMode: one-shot` keeps omitted or `false` calls in the foreground and lets explicit `run_in_background: true` return a generic Job id. Full presets already carry `tool-jobs`, while the base host carries the job registry; retain both so `job_output`, `job_list`, `job_kill`, cancellation, and completion notices stay available. Installing a Bundle or composing a preset row does not start a product, authenticate an account, select a model, probe credentials, or manage native product settings. ## What not to move into a preset `agent-loop` registers the one agent factory and throws on a second. The registries own the per-session layering and cannot themselves be per-session. Session persistence must stay host-side or the session list fragments. The sandbox, approval, and permission rows are a deliberate boundary: a preset is exactly as privileged as the plugins it names, so letting one relax its own confinement would defeat the confinement. " - button "Inspect" -- button "Think The skill is loaded." +- button "Think" - paragraph: DONE - button "Copy" - button "Good response" diff --git a/snapshots/web/steering/mid-steer.expected.md b/snapshots/web/steering/mid-steer.expected.md index 18b8b2bda0..f8b2fc5561 100644 --- a/snapshots/web/steering/mid-steer.expected.md +++ b/snapshots/web/steering/mid-steer.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Use the ask_user_question tool to ask me exactly one question with id "checkpoint", question "Ready to continue?", header "Checkpoint", and options labeled "Yes" and "No". After I answer, reply with one short sentence acknowledging my answer and stop. {{clock}} - button "Copy" - button "Context injection runtime-context" diff --git a/snapshots/web/steering/settled-expanded.expected.md b/snapshots/web/steering/settled-expanded.expected.md index 558a2cbccd..037a6f71da 100644 --- a/snapshots/web/steering/settled-expanded.expected.md +++ b/snapshots/web/steering/settled-expanded.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Use the ask_user_question tool to ask me exactly one question with id "checkpoint", question "Ready to continue?", header "Checkpoint", and options labeled "Yes" and "No". After I answer, reply with one short sentence acknowledging my answer and stop. {{clock}} - button "Copy" - button "1 tool call" [expanded] diff --git a/snapshots/web/steering/settled.expected.md b/snapshots/web/steering/settled.expected.md index 9d5e8bbdc5..b1cb14742e 100644 --- a/snapshots/web/steering/settled.expected.md +++ b/snapshots/web/steering/settled.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Use the ask_user_question tool to ask me exactly one question with id "checkpoint", question "Ready to continue?", header "Checkpoint", and options labeled "Yes" and "No". After I answer, reply with one short sentence acknowledging my answer and stop. {{clock}} - button "Copy" - button "1 tool call" diff --git a/snapshots/web/subagent-conversation/sidebar-chat.expected.md b/snapshots/web/subagent-conversation/sidebar-chat.expected.md index 588d7bc778..2563dc0d92 100644 --- a/snapshots/web/subagent-conversation/sidebar-chat.expected.md +++ b/snapshots/web/subagent-conversation/sidebar-chat.expected.md @@ -1,4 +1,3 @@ -- button "System prompt" - text: "Explain event sourcing in one sentence.Your parent agent id is \"session-{{uuid}}\". Before you finish, send your result to that agent with send_message({ agent_id: \"session-{{uuid}}\", message: \"\" }). The parent shares your workspace but does not automatically receive your transcript, tool output, or reasoning. Send earlier messages as well when a finding changes what the parent should do next; sending a message does not end your turn. {{clock}}" - button "Copy" - button "Thought for a while" diff --git a/snapshots/web/subagent-conversation/ui-expanded.expected.md b/snapshots/web/subagent-conversation/ui-expanded.expected.md index 958a6e5041..c4a77f1285 100644 --- a/snapshots/web/subagent-conversation/ui-expanded.expected.md +++ b/snapshots/web/subagent-conversation/ui-expanded.expected.md @@ -13,23 +13,20 @@ - navigation "Turn navigation": - button "Jump to turn 1" - button "Jump to turn 2" -- button "System prompt" - text: "Explain event sourcing in one sentence.Your parent agent id is \"session-{{uuid}}\". Before you finish, send your result to that agent with send_message({ agent_id: \"session-{{uuid}}\", message: \"\" }). The parent shares your workspace but does not automatically receive your transcript, tool output, or reasoning. Send earlier messages as well when a finding changes what the parent should do next; sending a message does not end your turn. {{clock}}" - button "Copy" - button "Thought for a while" [expanded] - button "Context injection runtime-context" -- button "Think The user is asking for a one-sentence description of event sourcing. This is a straightforward knowledge question that doesn't require any skill loading or tool calls." +- button "Think" - paragraph: Event sourcing is a pattern where all changes to an application's state are stored as an immutable, append-only sequence of events, rather than persisting only the current state, enabling full auditability, temporal queries, and event-driven architectures. - button "Copy" - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- text: {{clock}} -- button "System prompt" -- text: Now give the same explanation to a human reader. {{clock}} +- text: {{clock}} Now give the same explanation to a human reader. {{clock}} - button "Copy" - button "Thought for a while" [expanded] -- button "Think The user is asking for a one-sentence description of event sourcing. This is a straightforward knowledge question that doesn't require any skill loading or tool calls." +- button "Think" - paragraph: Event sourcing is a pattern where all changes to an application's state are stored as an immutable, append-only sequence of events, rather than persisting only the current state, enabling full auditability, temporal queries, and event-driven architectures. - button "Copy" - button "Good response" diff --git a/snapshots/web/subagent-conversation/ui.expected.md b/snapshots/web/subagent-conversation/ui.expected.md index 62af856938..5e1ccfc3fa 100644 --- a/snapshots/web/subagent-conversation/ui.expected.md +++ b/snapshots/web/subagent-conversation/ui.expected.md @@ -13,7 +13,6 @@ - navigation "Turn navigation": - button "Jump to turn 1" - button "Jump to turn 2" -- button "System prompt" - text: "Explain event sourcing in one sentence.Your parent agent id is \"session-{{uuid}}\". Before you finish, send your result to that agent with send_message({ agent_id: \"session-{{uuid}}\", message: \"\" }). The parent shares your workspace but does not automatically receive your transcript, tool output, or reasoning. Send earlier messages as well when a finding changes what the parent should do next; sending a message does not end your turn. {{clock}}" - button "Copy" - button "Thought for a while" @@ -22,9 +21,7 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- text: {{clock}} -- button "System prompt" -- text: Now give the same explanation to a human reader. {{clock}} +- text: {{clock}} Now give the same explanation to a human reader. {{clock}} - button "Copy" - button "Thought for a while" - paragraph: Event sourcing is a pattern where all changes to an application's state are stored as an immutable, append-only sequence of events, rather than persisting only the current state, enabling full auditability, temporal queries, and event-driven architectures. diff --git a/snapshots/web/subagent-interrupt/offline-composer.expected.md b/snapshots/web/subagent-interrupt/offline-composer.expected.md index 32ef6d7bd7..7c67669374 100644 --- a/snapshots/web/subagent-interrupt/offline-composer.expected.md +++ b/snapshots/web/subagent-interrupt/offline-composer.expected.md @@ -9,7 +9,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: "Explain event sourcing in one sentence.Your parent agent id is \"session-{{uuid}}\". Before you finish, send your result to that agent with send_message({ agent_id: \"session-{{uuid}}\", message: \"\" }). The parent shares your workspace but does not automatically receive your transcript, tool output, or reasoning. Send earlier messages as well when a finding changes what the parent should do next; sending a message does not end your turn. {{clock}}" - button "Copy" - button "Context injection runtime-context" diff --git a/snapshots/web/turn-tail-actions/completed.expected.md b/snapshots/web/turn-tail-actions/completed.expected.md index 88cbf864a8..52872ef7db 100644 --- a/snapshots/web/turn-tail-actions/completed.expected.md +++ b/snapshots/web/turn-tail-actions/completed.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Begin your reply with the plain sentence "Reading the workspace now." as text, and in that same message call the bash tool with the command "echo alpha". After the tool result, reply with the single word DONE and stop. {{clock}} - button "Copy" - button "1 tool call · 1 message" diff --git a/snapshots/web/turn-tail-actions/focused.expected.md b/snapshots/web/turn-tail-actions/focused.expected.md index 97ce445aef..cd8c64c32e 100644 --- a/snapshots/web/turn-tail-actions/focused.expected.md +++ b/snapshots/web/turn-tail-actions/focused.expected.md @@ -6,12 +6,11 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Begin your reply with the plain sentence "Reading the workspace now." as text, and in that same message call the bash tool with the command "echo alpha". After the tool result, reply with the single word DONE and stop. {{clock}} - button "Copy" - button "1 tool call · 1 message" [expanded] - button "Context injection runtime-context" -- button "Think The user wants me to begin with \"Reading the workspace now.\" and call bash with \"echo alpha\" in the same message. Then after the tool result, reply with the single word DONE and stop." +- button "Think" - paragraph: Reading the workspace now. - button "Bash Print alpha to stdout" - paragraph: DONE diff --git a/snapshots/web/turn-tail-actions/running.expected.md b/snapshots/web/turn-tail-actions/running.expected.md index 0aad69b556..ce077f8d64 100644 --- a/snapshots/web/turn-tail-actions/running.expected.md +++ b/snapshots/web/turn-tail-actions/running.expected.md @@ -6,12 +6,11 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Begin your reply with the plain sentence "Reading the workspace now." as text, and in that same message call the bash tool with the command "echo alpha". After the tool result, reply with the single word DONE and stop. {{clock}} - button "Copy" - tooltip "Copy" - button "Context injection runtime-context" -- button "Think The user wants me to begin with \"Reading the workspace now.\" and call bash with \"echo alpha\" in the same message. Then after the tool result, reply with the single word DONE and stop." +- button "Think" - paragraph: Reading the workspace now. - button "Bash Print alpha to stdout" - paragraph: partial diff --git a/snapshots/web/turn-tail-actions/settled.expected.md b/snapshots/web/turn-tail-actions/settled.expected.md index 33ff59bd2a..df291fa049 100644 --- a/snapshots/web/turn-tail-actions/settled.expected.md +++ b/snapshots/web/turn-tail-actions/settled.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Begin your reply with the plain sentence "Reading the workspace now." as text, and in that same message call the bash tool with the command "echo alpha". After the tool result, reply with the single word DONE and stop. {{clock}} - button "Copy" - button "1 tool call · 1 message" diff --git a/snapshots/web/turn-tail-actions/usage-expanded.expected.md b/snapshots/web/turn-tail-actions/usage-expanded.expected.md index ea6ffa712d..19a3319879 100644 --- a/snapshots/web/turn-tail-actions/usage-expanded.expected.md +++ b/snapshots/web/turn-tail-actions/usage-expanded.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Begin your reply with the plain sentence "Reading the workspace now." as text, and in that same message call the bash tool with the command "echo alpha". After the tool result, reply with the single word DONE and stop. {{clock}} - button "Copy" - button "1 tool call · 1 message" diff --git a/snapshots/web/web-search-round/ui.expected.md b/snapshots/web/web-search-round/ui.expected.md index a843fffa55..b769848c9f 100644 --- a/snapshots/web/web-search-round/ui.expected.md +++ b/snapshots/web/web-search-round/ui.expected.md @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Use web_search once with queries ["DeepSeek Harness snapshot search","DeepSeek Harness multi-query search"]. Then reply exactly SEARCH_DONE and stop. {{clock}} - button "Copy" - button "1 tool call" [expanded] diff --git a/snapshots/web/workflow-run/ui.expected.md b/snapshots/web/workflow-run/ui.expected.md index da34c06fd8..cd0ee5f743 100644 --- a/snapshots/web/workflow-run/ui.expected.md +++ b/snapshots/web/workflow-run/ui.expected.md @@ -1,12 +1,11 @@ -- button "System prompt" - text: "Use the workflow tool exactly once, with args omitted, meta set to { \"name\": \"snapshot-flow\", \"description\": \"one child for the snapshot\" }, and this EXACT script body (copy it verbatim): phase('Run') const reply = await agent('Reply with exactly the word WF_CHILD_OK and nothing else.') return { reply } After the workflow returns, reply with the single word WORKFLOW_DONE and stop. Do not use any other tool. {{clock}}" - button "Copy" - button "1 tool call" [expanded] - button "Context injection runtime-context" -- button "Think The user wants me to use the workflow tool exactly once with specific parameters. Let me carefully follow the instructions:" +- button "Think" - button "Run workflow snapshot-flow" - button "snapshot-flow 1 member Completed" -- button "Think The workflow returned successfully with the reply \"WF_CHILD_OK\". Now I need to reply with exactly \"WORKFLOW_DONE\" and stop." +- button "Think" - paragraph: WORKFLOW_DONE - button "Copy" - button "Good response" From c7e6e36dd11c2ba1c750b42318608efdb367b7cb Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Sun, 20 Sep 2026 23:22:13 +0800 Subject: [PATCH 24/27] fix(web): keep a superseded creation notice silent and add its e2e MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review follow-ups on the refused-creation notice: - `openWorkspace` raises `createFailed` only while its navigation is current, so a refusal that lands after a later navigation or owner disposal stays silent — the gate `initializeDefaultWorkspace` already uses and what the README states; two service cases pin it. - `RowActionToast` switches on the closed notice union and ends in `assertNever`, so an unhandled kind fails to compile instead of rendering another notice's copy. - `apps/web/tests/new-session-refused.e2e.ts` drives the composed Web server with a user preset whose row cannot resolve and compares the notice's ARIA golden, beside the default-Workspace failure scenario. - `@throws` on `openWorkspace` covers every failure (catalog regenerated); `RowToast.createFailed` records why the Host code stays in the copy; the README states that other failures show their own message. --- .../new-session-refused/notice.expected.md | 1 + apps/web/tests/new-session-refused.e2e.ts | 70 +++++++++++++++++++ apps/web/tsconfig.json | 1 + packages/client/ui-workspace/README.i18n.yaml | 4 +- packages/client/ui-workspace/README.md | 2 +- packages/client/ui-workspace/README.zh.md | 2 +- .../ui-workspace/src/client/contract/slots.ts | 6 +- .../ui-workspace/src/client/navigation.ts | 14 ++-- .../client/session-actions/RowActionToast.tsx | 25 +++++-- .../tests/workspaces-service.client.spec.ts | 12 ++++ .../src/client/api-catalog.ts | 2 +- tsconfig.host.json | 1 + 12 files changed, 122 insertions(+), 18 deletions(-) create mode 100644 apps/web/tests/expected/new-session-refused/notice.expected.md create mode 100644 apps/web/tests/new-session-refused.e2e.ts diff --git a/apps/web/tests/expected/new-session-refused/notice.expected.md b/apps/web/tests/expected/new-session-refused/notice.expected.md new file mode 100644 index 0000000000..52e7072f0f --- /dev/null +++ b/apps/web/tests/expected/new-session-refused/notice.expected.md @@ -0,0 +1 @@ +- alert: "新建会话失败:agent-preset/invalid: agent-presets: preset \"renamed-plugin\" failed to mount: row \"ghost\" names a plugin that cannot be resolved: @deepseek-ai/dsh-no-such-plugin" diff --git a/apps/web/tests/new-session-refused.e2e.ts b/apps/web/tests/new-session-refused.e2e.ts new file mode 100644 index 0000000000..80dcb8e990 --- /dev/null +++ b/apps/web/tests/new-session-refused.e2e.ts @@ -0,0 +1,70 @@ +/** An explicit New Session the Host refuses reports through the Workspace notice in the shipped Web composition. */ +import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { chromium } from 'playwright' +import { describe, expect, it, onTestFinished } from 'vitest' +import { compareOrRefreshGolden, launchWebScaffold, watchConsole, webSnapshotMode } from './scaffold.ts' +import { saveFailureShot } from './support.ts' + +const NOTICE_EXPECTED = fileURLToPath(new URL('./expected/new-session-refused/notice.expected.md', import.meta.url)) +const MODE = webSnapshotMode() +/** The default preset of this lane: its one row names a package the Host cannot resolve, as a preset copied before a plugin rename does. */ +const PRESET_ID = 'renamed-plugin' + +/** + * Seed a user preset root holding one preset the roster reads as broken. + * + * Discovery reports the unresolvable row before any mount, so the refusal + * carries no temp path and the notice text is stable across runs. + * @param root - the lane-owned preset root. + */ +async function seedBrokenPreset(root: string): Promise { + const directory = join(root, PRESET_ID) + await mkdir(directory, { recursive: true }) + await writeFile(join(directory, 'agent.cordis.yml'), '- id: ghost\n name: \'@deepseek-ai/dsh-no-such-plugin\'\n') + await writeFile(join(directory, 'preset.yml'), 'name: Renamed plugin\ndescription: Names a plugin that no longer resolves.\n') +} + +describe.skipIf(MODE === 'record')('web e2e: refused New Session', () => { + it('shows the Host refusal as a notice and leaves the Workspace without a Session', async () => { + const presetRoot = await realpath(await mkdtemp(join(tmpdir(), 'dsh-web-e2e-broken-preset-'))) + onTestFinished(() => rm(presetRoot, { recursive: true, force: true })) + await seedBrokenPreset(presetRoot) + const scaffold = await launchWebScaffold({ + firstUse: true, + agentPresets: { roots: [{ path: presetRoot, trust: 'user' }], default: PRESET_ID }, + }) + onTestFinished(() => scaffold.close()) + const browser = await chromium.launch() + try { + const page = await browser.newPage({ locale: 'zh-CN', timezoneId: 'Asia/Shanghai' }) + const tripwire = watchConsole(page) + try { + await page.goto(scaffold.authenticatedUrl) + // Startup prepares the default Workspace, and its own blank-Session + // attempt is refused without a notice: the hero stays on the picker. + await page.getByRole('button', { name: '选择工作区', exact: true }).waitFor() + await expect.poll(() => scaffold.ctx.workspaceRegistry.list().length).toBe(1) + expect(scaffold.ctx.sessions.list()).toEqual([]) + expect(await page.getByRole('alert').count()).toBe(0) + + await page.getByRole('button', { name: '新建会话', exact: true }).first().click() + const notice = page.getByRole('alert').filter({ hasText: '新建会话失败' }) + await notice.waitFor() + await compareOrRefreshGolden(NOTICE_EXPECTED, await notice.ariaSnapshot(), MODE) + expect(scaffold.ctx.sessions.list()).toEqual([]) + expect(scaffold.ctx.workspaceRegistry.list()).toHaveLength(1) + expect(await page.locator('[data-composer-input][contenteditable="true"]').count()).toBe(0) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + } catch (error) { + await saveFailureShot(page, 'web-e2e-new-session-refused') + throw error + } + } finally { + await browser.close() + } + }) +}) diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 8560d4f99e..4e8faba00b 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -64,6 +64,7 @@ "tests/models-settings-recovery.e2e.ts", "tests/default-model.e2e.ts", "tests/default-workspace.e2e.ts", + "tests/new-session-refused.e2e.ts", "tests/github-ready-review.e2e.ts", "tests/streaming-fence-highlight.e2e.ts", "tests/declared-reasoning.e2e.ts", diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index 6c1b132770..3a35e45163 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-workspace/README.md -README.md: d4396fd07a05791285f44a01a6cfb17aeac1ebe9 -README.zh.md: 31dca87e21c620271f5fe7307f07f9f437247742 +README.md: 3fd9308f0f47a561a08f831f7d923aad2863a25b +README.zh.md: 97bcac6456bb68606a4747984c24f5f618fa9bb4 diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index d4396fd07a..3fd9308f0f 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -69,7 +69,7 @@ The value is intentionally best effort for cold Sessions. An identity-matching u Navigation and startup restoration obtain the selected Session's projections from its `follow`; neither issues a separate projection refresh for that Session or its parent. -New Session tries to acquire the first eligible blank in catalog order; startup restoration tries the saved blank. If that writer is held, navigation creates a new Session without trying other blanks. Other acquisition failures abort the request: an explicit New Session or hero Workspace pick shows the failure as a transient notice quoting the Host's code and message (for example a preset that fails to mount), while startup restoration reports only to the console. Released blanks retain their slash-command state when reused. Later navigation cancels a pending startup selection. +New Session tries to acquire the first eligible blank in catalog order; startup restoration tries the saved blank. If that writer is held, navigation creates a new Session without trying other blanks. Other acquisition failures abort the request: an explicit New Session or hero Workspace pick shows the failure as a transient notice quoting the Host's code and message (for example a preset that fails to mount) or, for a failure that is not a Host refusal, that failure's own message; a request a later navigation or owner disposal superseded raises no notice, and startup restoration reports only to the console. Released blanks retain their slash-command state when reused. Later navigation cancels a pending startup selection. Once both Workspace and Session startup baselines are ready, an empty installation calls `workspaces.initializeDefault` and creates or reuses its blank Session. The composer becomes editable when that Session is selected; no message is submitted automatically. Later navigation or owner disposal prevents startup from selecting its result. Ineligible first use leaves the folder picker available without an error. Default Workspace creation failure shows a transient notice directing the user to Choose workspace, and is not retried until the next startup. Session creation failures use the ordinary restoration error handling. The registered Workspace remains available if Session creation or later submission fails. diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index 31dca87e21..97bcac6456 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -69,7 +69,7 @@ Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示** 导航和启动恢复通过所选 Session 的 `follow` 获取投影,不会另行刷新该 Session 或其父会话的投影。 -新建会话尝试获取列表中第一个符合条件的空白会话;启动恢复尝试已保存的空白会话。若该写锁被占用,导航直接新建 Session,不再尝试其他空白会话。其他获取错误会中止请求:显式新建会话或在 hero 中选择工作区时,失败以短暂提示展示,引用 Host 的错误码和消息(例如 preset 挂载失败);启动恢复仍只报告到控制台。已释放的空白会话被复用时保留 slash 命令状态。后续导航会取消尚未完成的启动选择。 +新建会话尝试获取列表中第一个符合条件的空白会话;启动恢复尝试已保存的空白会话。若该写锁被占用,导航直接新建 Session,不再尝试其他空白会话。其他获取错误会中止请求:显式新建会话或在 hero 中选择工作区时,失败以短暂提示展示,引用 Host 的错误码和消息(例如 preset 挂载失败),非 Host 拒绝的失败则显示其自身消息;已被后续导航或 owner 销毁取代的请求不弹提示,启动恢复仍只报告到控制台。已释放的空白会话被复用时保留 slash 命令状态。后续导航会取消尚未完成的启动选择。 Workspace 和 Session 的启动基线均就绪后,空安装环境调用 `workspaces.initializeDefault`,创建或复用其空白 Session。选中该 Session 后输入框才可编辑,不会自动提交消息。后续导航或所属上下文销毁会阻止启动流程选中其结果。不符合首次使用条件时仍可选择文件夹,不显示错误。默认工作区创建失败时显示短暂提示,引导用户通过“选择工作区”选择文件夹,直到下次启动才重试。Session 创建失败沿用普通的恢复错误处理。登记成功的工作区在 Session 创建或后续提交失败时仍然保留。 diff --git a/packages/client/ui-workspace/src/client/contract/slots.ts b/packages/client/ui-workspace/src/client/contract/slots.ts index 0bd651602a..c37fa75e73 100644 --- a/packages/client/ui-workspace/src/client/contract/slots.ts +++ b/packages/client/ui-workspace/src/client/contract/slots.ts @@ -245,7 +245,11 @@ export type RowToast = | { kind: 'unpinFailed' } | { kind: 'archivedNotOpenable' } | { kind: 'defaultWorkspaceFailed' } - /** An explicit New Session request the Host refused; `message` is the failure in the Host's own words, untranslated. */ + /** + * An explicit New Session request that failed. `message` is untranslated: + * a Host refusal as `code: message` — the stable code stays in the copy so + * a report can be searched by it — and any other failure's own message. + */ | { kind: 'createFailed'; message: string } /** The notice on display; `seq` keys remounts so a repeated notice restarts its hold. */ diff --git a/packages/client/ui-workspace/src/client/navigation.ts b/packages/client/ui-workspace/src/client/navigation.ts index 4a05f3fc62..eefaab86b5 100644 --- a/packages/client/ui-workspace/src/client/navigation.ts +++ b/packages/client/ui-workspace/src/client/navigation.ts @@ -39,7 +39,8 @@ export interface UiWorkspace { * @param workspaceId - target Workspace. * @param beforeOpen - optional synchronous preparation for the selected Session, skipped after supersession. * @returns completion; a superseded request may create a Session but does not open it. - * @throws when the Session cannot be created; the failure is also shown through the Workspace notice. + * @throws on failure; a refused creation is also shown through the Workspace + * notice unless a later navigation or disposal superseded the request. */ openWorkspace(workspaceId: WorkspaceId, beforeOpen?: (sessionId: SessionId) => void): Promise /** @@ -205,9 +206,9 @@ class UiWorkspaceService extends Service implements UiWorkspace { try { sessionId = await this.connectWorkspace(workspaceId) } catch (error: unknown) { - // The user asked for this Session, so the refusal is theirs to read; - // startup restoration goes through connectWorkspace directly and stays quiet. - this.notify({ kind: 'createFailed', message: creationFailureMessage(error) }) + // Reported here, not in connectWorkspace: startup restoration calls that + // directly and stays console-only. + if (!navigation.aborted) this.notify({ kind: 'createFailed', message: creationFailureMessage(error) }) throw error } if (navigation.aborted) return @@ -410,8 +411,9 @@ class UiWorkspaceService extends Service implements UiWorkspace { } /** - * The Session Controller's creation failure `error` is, or undefined. Client - * plugin bundles do not share error-class identity, so the name decides. + * `error` as the Session Controller's creation failure, or undefined when it + * is not one. Client plugin bundles do not share error-class identity, so the + * name decides. */ function sessionCreateErrorOf(error: unknown): SessionCreateError | undefined { return error instanceof Error && error.name === 'SessionCreateError' ? error as SessionCreateError : undefined diff --git a/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx b/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx index 7833409ba8..cbc7076dc7 100644 --- a/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx +++ b/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx @@ -3,7 +3,8 @@ * One notice is visible at a time; a parent rerender does not extend its hold. */ import { IconWarningOutlineRegular, Toast } from '@deepseek-ai/dsh-client-ui-primitives' -import type { RowToastProps } from '../contract/slots.ts' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import type { RowToastProps, RowToastState } from '../contract/slots.ts' /** * Hold for the notices that take longer to read than a one-line warning: the @@ -50,16 +51,28 @@ export function RowActionToast({ useToast, dismissToast, undoArchive, showArchiv /> ) } - const text = toast.kind === 'pinFailed' - ? t('toast.pinFailed') - : toast.kind === 'unpinFailed' ? t('toast.unpinFailed') - : toast.kind === 'defaultWorkspaceFailed' ? t('defaultWorkspace.failed') : t('toast.archivedNotOpenable') return ( } onDone={dismissToast} /> ) } + +/** The copy of one plain warning, keyed by the notice kind the union closes over. */ +function plainNoticeText( + toast: Exclude, + t: RowToastProps['t'], +): string { + switch (toast.kind) { + case 'pinFailed': return t('toast.pinFailed') + case 'unpinFailed': return t('toast.unpinFailed') + case 'defaultWorkspaceFailed': return t('defaultWorkspace.failed') + case 'archivedNotOpenable': return t('toast.archivedNotOpenable') + /* v8 ignore next 2 -- closed-union backstop; only reached if a notice kind is forged */ + default: + return assertNever(toast) + } +} diff --git a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts index 10fe3fdb65..fd8e77e237 100644 --- a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts +++ b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts @@ -490,6 +490,18 @@ describe('UiWorkspaceService', () => { } }) + it.each(['disposal', 'a later navigation'] as const)('keeps a creation refused after %s silent', async (kind) => { + const b = bench({ workspaces: workspaceState([workspace('a')]) }) + const created = Promise.withResolvers() + b.sessions.create.mockReturnValueOnce(created.promise) + const pending = b.uiWorkspace.openWorkspace(wid('a')) + if (kind === 'disposal') await b.ctx.fiber.dispose() + else b.uiWorkspace.openSession(sid('elsewhere')) + created.reject(new Error('late refusal')) + await expect(pending).rejects.toThrow('late refusal') + expect(b.notify).not.toHaveBeenCalled() + }) + it('ignores a rejected startup selection and stale catalog callbacks after disposal', async () => { const created = Promise.withResolvers() const warning = vi.spyOn(console, 'warn').mockImplementation(() => undefined) 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 fe5358eef9..6fe1e49f41 100644 --- a/packages/extensions/cordis-client-runner/src/client/api-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/api-catalog.ts @@ -345,7 +345,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ description: 'Connect a Workspace and open its Session unless a later navigation supersedes it.', parameters: [{ name: 'workspaceId', description: 'target Workspace.' }, { name: 'beforeOpen', description: 'optional synchronous preparation for the selected Session, skipped after supersession.' }], returns: 'completion; a superseded request may create a Session but does not open it.', - throws: ['when the Session cannot be created; the failure is also shown through the Workspace notice.'], + throws: ['on failure; a refused creation is also shown through the Workspace notice unless a later navigation or disposal superseded the request.'], }, { signature: 'forkSession(sessionId: SessionId): Promise', diff --git a/tsconfig.host.json b/tsconfig.host.json index 5285dffbe3..e15bf83b24 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -65,6 +65,7 @@ "apps/web/tests/workspace-new-session-folding.e2e.ts", "apps/web/tests/workspace-management.e2e.ts", "apps/web/tests/default-workspace.e2e.ts", + "apps/web/tests/new-session-refused.e2e.ts", "apps/web/tests/workspace-recency.e2e.ts", "apps/web/tests/session-unarchive.e2e.ts", "apps/web/tests/replay-round-trip.e2e.ts", From c3c3d95608ebe26a6cfa8acad4f3197515e00ddd Mon Sep 17 00:00:00 2001 From: imccyu Date: Sun, 20 Sep 2026 23:36:20 +0800 Subject: [PATCH 25/27] test(web): align preview and fence checks with chat folding --- apps/web/tests/preview-boot.e2e.ts | 9 +++++++-- .../streaming-fence-highlight/mid-stream.expected.md | 1 - 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/apps/web/tests/preview-boot.e2e.ts b/apps/web/tests/preview-boot.e2e.ts index bde54fe69e..270f19a181 100644 --- a/apps/web/tests/preview-boot.e2e.ts +++ b/apps/web/tests/preview-boot.e2e.ts @@ -40,7 +40,7 @@ import { buildVfsExampleFiles, } from '../../../packages/experimental/webworker-runtime/tests/vfs-example-fixture.ts' import { captureStableAria, compareOrRefreshGolden, webSnapshotMode } from './scaffold.ts' -import { newEnglishPage, REPO_ROOT, saveFailureShot } from './support.ts' +import { expandOwningTurnProcess, newEnglishPage, REPO_ROOT, saveFailureShot } from './support.ts' const DIST_ROOT = fileURLToPath(new URL('../dist', import.meta.url)) @@ -418,12 +418,17 @@ async function bootPreview(origin: string, browser: Browser): Promise { await page.getByText(SHOWCASE_TAIL, { exact: true }).waitFor({ timeout: 30_000 }) expect(await page.getByText(SHOWCASE_OLDEST, { exact: true }).count()).toBe(0) + // Complete Turns can fold while earlier history is still unloaded. + const readTool = page.locator('[data-chat-call-id="preview-read"]') + await readTool.waitFor({ state: 'attached' }) + expect(await readTool.isVisible()).toBe(false) + await expandOwningTurnProcess(page, readTool) await page.getByRole('button', { name: 'PREVIEW.md', exact: true }).waitFor() await page.getByRole('button', { name: 'src/preview.ts', exact: true }).waitFor() await page.getByText('Update to-do list', { exact: true }).waitFor() await page.getByText('Error: ENOENT: no such file, open missing.txt', { exact: true }).waitFor() - const subagents = page.getByRole('button', { name: '2 subagents' }) + const subagents = page.getByRole('button', { name: '2 subagents', exact: true }) await subagents.waitFor({ timeout: 15_000 }) await subagents.hover() const catalog = page.getByRole('tree', { name: 'Subagent sessions' }) 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 27e4c283ae..19c2becc76 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 @@ -6,7 +6,6 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" -- button "System prompt" - text: Stream one TypeScript fence for the highlighting snapshot. {{clock}} - button "Copy" - button "Context injection runtime-context" From 3f7016a4226777b2898eb1919f1527ab9915bbcd Mon Sep 17 00:00:00 2001 From: Turtle Date: Mon, 21 Sep 2026 00:04:06 +0800 Subject: [PATCH 26/27] feat(config): add volatile schemas and watcher-driven updates (#4579) * feat(cordis): add volatile config references without remounting * refactor(cordis): use internal prefix for volatile updates * fix(schemastery): preserve metadata-free serialized schemas * refactor(config): move volatile updates into an opt-in Loader plugin * refactor(config): reuse Loader context patch for volatile updates * refactor(config): let the volatile watcher commit equal candidates * refactor(config): separate comparison from volatile reconciliation * refactor(loader): extract pure entry option diff * refactor(loader): compare volatile config through schema metadata * refactor(loader): make volatile comparison policy explicit * refactor: name config reload and volatile HMR events * refactor(loader): compare volatile config in one schema walk; declare hmr/volatile-update in volatile-hmr Replace the mask/project pair in vendor/loader/src/config/diff.ts with one recursive schema-guided comparison. Absent objects now compare as their declared schema default at every object node, not only under volatile ancestors; both inputs resolve to the same validated config, so the one changed assertion (undefined vs {} under a non-volatile object schema) becomes unchanged. The isJsExpr special case is dropped: expression keys fall through to raw comparison. Move the hmr/volatile-update Events declaration from vendored Cordis core to its producer, packages/boot/volatile-hmr, matching how dsh-hmr declares hmr/change and hmr/reload. Vendored cordis events.ts returns to upstream content; the inherited Cordis API catalog and the event matrix are regenerated, and the tutorial example imports the package types. * fix(cosmokit): compare sparse array slots in deepEqual; extend volatile diff coverage Array.prototype.every skipped holes, so deepEqual(Array(1), ['new']) was true in one direction. Compare every index with holes read as undefined. config/diff.ts treats expression objects as opaque values even when a schema field shares the marker name, and looks up field schemas with Object.hasOwn so unknown keys named after Object prototype members compare raw. Tests cover absent-object defaults, sparse arrays in both directions, prototype-named keys, metadata-free serialized schema nodes, and a runtime remount check in volatile-hmr. READMEs and the architecture note describe the object-default rule. * test(schemastery): build serialized schema fixtures without unknown casts verify-no-unknown-casts rejects the two as-unknown assertions in scripts/volatile-config.spec.ts. Parse the serialized nodes from JSON text instead, matching scripts/loader-config-diff.spec.ts. * docs(volatile-hmr): drop the scope-scan tag from hmr/volatile-update verify-scoped-events rejects @dshScopeScan on an event that carries no scoped keys. Catalogs and the event matrix are regenerated. * docs: regenerate module graph for the volatile-hmr dependency edge verify-module-graph reports the merged docs stale: volatile-hmr now lists its app-boot dependency. * test(volatile-hmr): watch the real YAML through an exact config watch The Windows coverage lane lost the whole spec: its vitest worker exited without a report once this test started a chokidar directory watch (root: ['.']), the only real directory watch in the test suite. Register the include file through hmr.watchConfig instead, the pattern the HMR package's own real-file tests run on Windows, and emit loader/config-reload from the refresh callback as the root-watch path does. packages/boot/hmr/tests/coordination.spec.ts already covers that root-watch emission with a mocked watcher; volatile-hmr and hmr sources stay at 100% coverage. * test(volatile-hmr): pass the Include path as a file URL On Windows the plain absolute path made the include subtree fail to load, so the profile-patch test found no consumer entry. Other Include fixtures in this spec already pass file URLs. * refactor(loader): commit volatile config in Entry.update and remove volatile-hmr loader/config-reload was emitted from two places (app-boot profile reconciliation and the HMR root watch) and by hand in tests, because a separate plugin needed a "configuration applied" signal to run its own pass. Every update path already funnels through Entry.update, which is where the Loader decides to skip a remount for a volatile-only change. Entry._commitVolatile now parses the candidate through the fiber's internal/config hook and schema, commits the new values into the running references when the ordinary effective values still match, and emits loader/volatile-update to the owning fiber. A changed ordinary effective value falls back to the ordinary remount instead of leaving the instance stale; an invalid candidate is logged and keeps the running references, with the raw config retained for the next activation. Forced group updates take the same path. Remove packages/boot/volatile-hmr, its event, the app-boot loader/config-reload declaration and emit, and the HMR emission. Loader runtime and real-file tests move to scripts/loader-volatile-update.spec.ts. Docs, catalogs, the event matrix, module graph and the architecture note follow. * test: share the volatile schema fixture between the schema and Loader specs The duplication gate flagged the identical Config fixture in scripts/volatile-config.spec.ts and scripts/loader-volatile-update.spec.ts. * refactor(loader): reduce config/diff.ts to equalExceptVolatile Entry.update now computes the strict raw option changes itself and only asks diff.ts whether two raw configs differ at most in volatile fields. The ignoreVolatile flag, the options object and the "config is the sole change" rule leave diff.ts; they were the Loader's decision and now sit next to the commit they gate. The raw-config deepEqual in the volatile branch is gone because the strict change list already answers it. * refactor(loader): type the volatile comparison against Schemastery's Schema config/diff.ts narrows the plugin's Standard Schema to Schemastery's own Schema type instead of a hand-written structural interface, which makes vendor/loader a type-only dependent of @deepseek-ai/schemastery. The rescope codemod treats the vendor identifier comparison like schemastery's own source and renames the import through an exact edit. * fix(loader): address review findings on the volatile commit path Entry.update only replaces the fiber's pending raw config for a volatile-only change, so a noSave direct update survives a no-op entry update. _commitVolatile logs at debug level when ordinary effective values changed and the ordinary update applies, dispatches loader/volatile-update with a Context receiver like Cordis' own filtered emits, and isolates a throwing listener. Schemastery reports unsupported volatile values as ValidationError with their path and validates a lazy inner once when it is built. The inherited-event catalog gains internal/config and corrected source lines; the Loader spec imports dsh-hmr by package name and covers the new behaviors. Docs record that class-instance ordinary fields always take the remount path and that .default() accepts the raw input type. --- ...09-18-volatile-config-references.i18n.yaml | 6 + .../2026-09-18-volatile-config-references.md | 33 + ...026-09-18-volatile-config-references.zh.md | 33 + docs/cordis-api/inherited.md | 28 +- docs/cordis-tutorial/05-config.i18n.yaml | 4 +- docs/cordis-tutorial/05-config.md | 27 + docs/cordis-tutorial/05-config.zh.md | 27 + packages/boot/app-boot/README.i18n.yaml | 4 +- packages/boot/app-boot/README.md | 2 +- packages/boot/app-boot/README.zh.md | 2 +- packages/boot/hmr/README.i18n.yaml | 4 +- packages/boot/hmr/README.md | 2 +- packages/boot/hmr/README.zh.md | 2 +- packages/boot/hmr/tests/modules.spec.ts | 26 + pnpm-lock.yaml | 3 + scripts/gen-cordis-catalog.ts | 28 +- scripts/loader-config-diff.spec.ts | 109 +++ scripts/loader-volatile-update.spec.ts | 634 ++++++++++++++++++ scripts/rescope-vendor.ts | 9 + scripts/volatile-config.fixture.ts | 11 + scripts/volatile-config.spec.ts | 151 +++++ vendor/README.md | 2 + vendor/cordis/README.md | 4 + vendor/cordis/src/index.ts | 2 + vendor/cosmokit/README.md | 6 + vendor/cosmokit/src/index.ts | 2 + vendor/cosmokit/src/types.ts | 70 +- vendor/cosmokit/src/volatile.ts | 86 +++ vendor/loader/README.md | 4 + vendor/loader/package.json | 3 +- vendor/loader/src/config/diff.ts | 45 ++ vendor/loader/src/config/entry.ts | 60 +- vendor/loader/src/index.ts | 14 +- vendor/loader/tsconfig.json | 3 + vendor/schemastery/README.md | 4 + vendor/schemastery/src/index.ts | 126 +++- 36 files changed, 1476 insertions(+), 100 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-09-18-volatile-config-references.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-09-18-volatile-config-references.md create mode 100644 .agents/notes/implemented/architecture/2026-09-18-volatile-config-references.zh.md create mode 100644 scripts/loader-config-diff.spec.ts create mode 100644 scripts/loader-volatile-update.spec.ts create mode 100644 scripts/volatile-config.fixture.ts create mode 100644 scripts/volatile-config.spec.ts create mode 100644 vendor/cosmokit/src/volatile.ts create mode 100644 vendor/loader/src/config/diff.ts diff --git a/.agents/notes/implemented/architecture/2026-09-18-volatile-config-references.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-18-volatile-config-references.i18n.yaml new file mode 100644 index 0000000000..ef7c78129d --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-18-volatile-config-references.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-18-volatile-config-references.md +2026-09-18-volatile-config-references.md: afaa6affdc3d18da182ec069126033cb55393b72 +2026-09-18-volatile-config-references.zh.md: 3d8800cb92dec4da80b698cb8b3c073331ed266f diff --git a/.agents/notes/implemented/architecture/2026-09-18-volatile-config-references.md b/.agents/notes/implemented/architecture/2026-09-18-volatile-config-references.md new file mode 100644 index 0000000000..afaa6affdc --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-18-volatile-config-references.md @@ -0,0 +1,33 @@ +# Agent Note: Volatile configuration references + +Status: implemented + +English | [中文](2026-09-18-volatile-config-references.zh.md) + +## Problem + +Replacing an entire plugin to change a value also disposes its services and effects. Separate settings subscriptions require each consumer to implement another source of live configuration. + +## Decision + +Schemastery declares live fields with `.volatile()`, preserving node types and form metadata while returning stable references to immutable snapshots. Cosmokit owns the shared protocol. General comparison treats two volatile references as equal. Loader calculates raw config differences using schema-declared volatile paths and retains raw config for subsequent activation. When the raw diff reports no ordinary change but the raw config differs, Loader parses and validates the candidate through the fiber's `internal/config` hook, compares ordinary effective values, commits references when those values still match, and notifies the owning fiber; every update path, including profile reconciliation, HMR Include refreshes and direct `entry.update()` calls, reaches this step through `Entry.update`. Fiber does not own this update policy, and HMR supplies file watching. + +Only volatile changes preserve the instance. Ordinary-field changes use the existing remount lifecycle and do not update the old references. An instance-local `loader/volatile-update` event reports paths after the complete candidate is validated and all references are committed. It uses ordinary `emit`; listener completion is not a configuration commit condition. References can be retained, while values may only be captured for one operation. Missing optional values retain a readable reference. + +Config schemas own the field types, defaults, roles, and live-update declaration needed by schema-driven settings forms. Existing settings consumers remain unchanged; automatic form generation and their migration are separate work. The [configuration guide](../../../../docs/cordis-tutorial/05-config.md) owns plugin-author usage. + +## Alternatives considered + +**Restart for every configuration change.** This releases resources that remain valid when only operation-time parameters change. + +**Add another settings-specific live-value API.** It duplicates runtime update semantics and makes plugins depend on settings to consume ordinary configuration. + +**Wrap values only during mounting.** Direct schema parsing would return a different kind of value from the plugin's config, requiring separate consumer types. + +## Consequences + +Schemas reject independent volatile references inside dynamic containers; entire objects and arrays can be volatile values. Immutable snapshots accept plain data. Simplification unwraps references, and shared symbols support ESM/CJS copies. Group/Include retain dispatch while volatile-only target updates bypass `internal/update`. Direct `fiber.update()` retains its semantics, including custom handling, saving and `noSave`. Loader commits live volatile updates itself; no separate plugin is required. + +Schema metadata keeps comparison independent of parsing: the diff does not execute expressions, validators or config hooks. Object nodes compare missing or null values using their declared defaults, even without volatile descendants; this avoids remounts for equivalent object defaults. Ordinary expression edits retain raw comparison even when they resolve to equal values. Loader compares parsed ordinary values, including URLs by normalized address. If an ordinary expression produces a different value, Loader applies the ordinary remount instead of committing; strict comparison treats class instances other than URL, Date and RegExp by identity, so an ordinary transform that builds a fresh instance per parse always remounts. Listener failures during the notification are logged and do not fail the update. Loader validates volatile candidates before committing; invalid edits remain in raw config but leave running references unchanged until a later activation. + +The schema and lifecycle regression suite covers direct updates, invalid candidates, instance isolation, dependency replacement, real file watching, and save/reload behavior. The HMR module suite covers replacement after live config updates. These tests do not claim settings migration or automatic form rendering. diff --git a/.agents/notes/implemented/architecture/2026-09-18-volatile-config-references.zh.md b/.agents/notes/implemented/architecture/2026-09-18-volatile-config-references.zh.md new file mode 100644 index 0000000000..3d8800cb92 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-18-volatile-config-references.zh.md @@ -0,0 +1,33 @@ +# Agent Note: Volatile 配置引用 + +Status: implemented + +[English](2026-09-18-volatile-config-references.md) | 中文 + +## Problem + +为了改变一个值而替换整个插件,也会销毁插件的服务和副作用。独立的 settings 订阅要求每个消费者额外实现一套动态配置来源。 + +## Decision + +Schemastery 使用 `.volatile()` 声明动态字段,保留节点类型和表单元数据,解析结果是具有不可变快照的稳定引用。共享协议位于 Cosmokit。通用比较将两个 volatile 引用视为相等。Loader 根据 schema 声明的 volatile 路径计算原始配置差异,并保留原始配置供后续激活使用。原始 diff 未报告普通字段变化但原始配置有差异时,Loader 经 fiber 的 `internal/config` 钩子解析并校验候选配置,比较普通字段的有效值,在这些值仍匹配时提交引用并通知所属实例;所有更新路径,包括 profile 重载、HMR 的 Include 刷新和直接调用 `entry.update()`,都经 `Entry.update` 到达这一步。Fiber 不承担这项更新策略,文件监视由 HMR 提供。 + +仅 volatile 变化保留实例。普通字段变化沿用现有重新挂载生命周期,不更新旧引用。实例局部的 `loader/volatile-update` 事件在完整候选配置通过校验且所有引用提交后报告路径。事件使用普通 `emit`;监听器完成不是配置提交条件。可以保存引用,而值只能在单次操作中保存。缺省可选值仍具有可读取的引用。 + +Config schema 负责提供基于 schema 的 settings 表单需要的字段类型、默认值、角色和动态更新声明。现有 settings 消费者保持不变;自动表单生成及其迁移是独立工作。[配置指南](../../../../docs/cordis-tutorial/05-config.zh.md)负责插件作者的使用说明。 + +## Alternatives considered + +**每次配置变化都重启。** 当只有操作时读取的参数变化时,这会释放仍然有效的资源。 + +**增加另一套 settings 专用动态值 API。** 这会重复运行时更新语义,并使插件为了读取普通配置而依赖 settings。 + +**仅在挂载时包装值。** 直接解析 schema 与插件配置将返回不同种类的值,需要独立的消费者类型。 + +## Consequences + +Schema 拒绝动态容器内部的独立 volatile 引用;整个对象和数组可以作为一个 volatile 值。不可变快照接受普通数据。配置简化解包引用,共享 symbol 支持 ESM/CJS 副本互操作。Group/Include 保留分发,目标插件的仅 volatile 更新不进入 `internal/update`。直接调用 `fiber.update()` 保留原语义,包括自定义处理、保存及 `noSave`。动态 volatile 更新由 Loader 自己提交,不需要额外插件。 + +Schema 元数据使比较独立于解析:diff 不执行表达式、校验器或配置钩子。对象节点的缺省值或 null 按声明的默认值比较,即使没有 volatile 后代字段;等价的对象默认值不触发重新挂载。普通表达式即使求值结果相等,修改时仍按原始值比较。Loader 比较解析后的普通值,其中 URL 按规范化地址比较。普通表达式产生不同值时,Loader 改为按普通流程重新挂载而不提交;严格比较对 URL、Date、RegExp 之外的类实例按身份比较,因此每次解析都产生新实例的普通 transform 字段总是走重新挂载。通知阶段监听器抛错只记录日志,不使更新失败。Loader 在提交前校验 volatile 候选;非法编辑保留在原始配置中,但在后续激活之前不改变运行中的引用。 + +Schema 和生命周期回归测试覆盖直接更新、无效候选、实例隔离、依赖替换、真实文件监视及保存后重新加载。HMR 模块测试覆盖动态配置更新后的代码替换。这些测试不代表 settings 迁移或自动表单渲染已经完成。 diff --git a/docs/cordis-api/inherited.md b/docs/cordis-api/inherited.md index bb6cd40bb3..cc62683cb5 100644 --- a/docs/cordis-api/inherited.md +++ b/docs/cordis-api/inherited.md @@ -21,16 +21,18 @@ This file is GENERATED from source (`scripts/gen-cordis-catalog.ts`) and verifie ## Inherited events (cordis core + loader/hmr/timer) -- `internal/plugin` — A plugin fiber was created. ([`vendor/cordis/src/events.ts:328`](../../vendor/cordis/src/events.ts)) -- `internal/status` — A fiber changed lifecycle state. ([`vendor/cordis/src/events.ts:330`](../../vendor/cordis/src/events.ts)) -- `internal/service` — Interception hook for a service binding (no core producer). ([`vendor/cordis/src/events.ts:332`](../../vendor/cordis/src/events.ts)) -- `internal/update` — Waterfall: a fiber config update is being applied. ([`vendor/cordis/src/events.ts:334`](../../vendor/cordis/src/events.ts)) -- `internal/get` — Waterfall: a service is being read from the store. ([`vendor/cordis/src/events.ts:336`](../../vendor/cordis/src/events.ts)) -- `internal/set` — Waterfall: a service is being written to the store. ([`vendor/cordis/src/events.ts:338`](../../vendor/cordis/src/events.ts)) -- `internal/listener` — A listener was registered. ([`vendor/cordis/src/events.ts:340`](../../vendor/cordis/src/events.ts)) -- `internal/dispatch` — An event is being dispatched to listeners. ([`vendor/cordis/src/events.ts:342`](../../vendor/cordis/src/events.ts)) -- `exit` — The process is exiting on a signal. ([`vendor/loader/src/index.ts:23`](../../vendor/loader/src/index.ts)) -- `loader/config-update` — The loader config tree changed. ([`vendor/loader/src/index.ts:24`](../../vendor/loader/src/index.ts)) -- `loader/entry-init` — A config entry is being initialized. ([`vendor/loader/src/index.ts:25`](../../vendor/loader/src/index.ts)) -- `loader/partial-dispose` — An entry is being partially disposed on reload. ([`vendor/loader/src/index.ts:26`](../../vendor/loader/src/index.ts)) -- `loader/patch-context` — A context is being patched during a reload. ([`vendor/loader/src/index.ts:27`](../../vendor/loader/src/index.ts)) +- `internal/plugin` — A plugin fiber was created. ([`vendor/cordis/src/events.ts:331`](../../vendor/cordis/src/events.ts)) +- `internal/status` — A fiber changed lifecycle state. ([`vendor/cordis/src/events.ts:333`](../../vendor/cordis/src/events.ts)) +- `internal/service` — Interception hook for a service binding (no core producer). ([`vendor/cordis/src/events.ts:341`](../../vendor/cordis/src/events.ts)) +- `internal/update` — Waterfall: a fiber config update is being applied. ([`vendor/cordis/src/events.ts:343`](../../vendor/cordis/src/events.ts)) +- `internal/config` — Waterfall: a fiber config is being resolved before validation. ([`vendor/cordis/src/events.ts:339`](../../vendor/cordis/src/events.ts)) +- `internal/get` — Waterfall: a service is being read from the store. ([`vendor/cordis/src/events.ts:345`](../../vendor/cordis/src/events.ts)) +- `internal/set` — Waterfall: a service is being written to the store. ([`vendor/cordis/src/events.ts:347`](../../vendor/cordis/src/events.ts)) +- `internal/listener` — A listener was registered. ([`vendor/cordis/src/events.ts:349`](../../vendor/cordis/src/events.ts)) +- `internal/dispatch` — An event is being dispatched to listeners. ([`vendor/cordis/src/events.ts:351`](../../vendor/cordis/src/events.ts)) +- `exit` — The process is exiting on a signal. ([`vendor/loader/src/index.ts:25`](../../vendor/loader/src/index.ts)) +- `loader/config-update` — The loader config tree changed. ([`vendor/loader/src/index.ts:26`](../../vendor/loader/src/index.ts)) +- `loader/entry-init` — A config entry is being initialized. ([`vendor/loader/src/index.ts:27`](../../vendor/loader/src/index.ts)) +- `loader/partial-dispose` — An entry is being partially disposed on reload. ([`vendor/loader/src/index.ts:28`](../../vendor/loader/src/index.ts)) +- `loader/patch-context` — A context is being patched during a reload. ([`vendor/loader/src/index.ts:41`](../../vendor/loader/src/index.ts)) +- `loader/volatile-update` — Volatile config values committed into the running fiber without a remount; dispatched to the owning fiber only. ([`vendor/loader/src/index.ts:34`](../../vendor/loader/src/index.ts)) diff --git a/docs/cordis-tutorial/05-config.i18n.yaml b/docs/cordis-tutorial/05-config.i18n.yaml index 2e7c3b22ec..3eb71ac95b 100644 --- a/docs/cordis-tutorial/05-config.i18n.yaml +++ b/docs/cordis-tutorial/05-config.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/cordis-tutorial/05-config.md -05-config.md: 17cccce2ec43be65477ce527800ee6a636ee5d96 -05-config.zh.md: e19dcb3ab0082cdc6ba2457158491ba47223409d +05-config.md: f278e8d06ef867d2944c279d067c36970582167f +05-config.zh.md: 65e9ea73a5ce31776dc1603339fa7c1c0250f856 diff --git a/docs/cordis-tutorial/05-config.md b/docs/cordis-tutorial/05-config.md index 17cccce2ec..f278e8d06e 100644 --- a/docs/cordis-tutorial/05-config.md +++ b/docs/cordis-tutorial/05-config.md @@ -67,6 +67,33 @@ ValidationError: invalid config: The plugin's fiber goes to FAILED, and this tutorial's launcher exits with status 1 after printing the error. A plugin should also reject schema-valid config that names an unavailable resource or provider as soon as it can resolve that reference. + +## Volatile fields + +Use `.volatile()` for a field that the plugin reads during each operation. A change to that field updates its stable reference without remounting the plugin. Read it with `.get()`: + +```ts +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/cordis-plugin-loader' +import Schema from '@deepseek-ai/schemastery' + +export const Config = Schema.object({ + greeting: Schema.string().default('Hello').volatile(), +}) + +export function apply(ctx: Context, config: ReturnType) { + ctx.on('loader/volatile-update', () => { + console.log(config.greeting.get()) + }) +} +``` + +A direct `Config(raw)` call also returns references. An optional field without a default still has a reference; `.get()` returns `undefined` when it is absent. Keep the reference, or capture its value for one operation, including across `await`. Do not retain that value for later operations. Object and array values are detached, recursively frozen snapshots of plain data; functions, class instances, and cycles are rejected. + +Loader compares raw config while ignoring schema-declared volatile fields. A volatile-only change is parsed through the plugin’s `internal/config` hook and validated; when every ordinary effective value still matches, Loader commits the new values into the running references and emits one instance-local `loader/volatile-update` with the changed paths as arrays of keys, bypassing the target plugin’s `internal/update`. Equal values do not notify. An invalid candidate is logged and leaves the running references unchanged until the next activation. A changed ordinary effective value, including a changed expression result, and simultaneous ordinary-field changes retain the existing update flow, leaving old references unchanged and unnotified. Group/Include still dispatch child updates. Direct `fiber.update()`, code replacement, and dependency replacement retain their lifecycle; `noSave` still controls direct-update persistence. Notifications use ordinary `emit` without awaiting resource reconfiguration. + +Declare volatile fields at fixed object paths, or mark an entire object or array volatile. Independent references inside arrays, dictionaries, union or intersect branches, lazy schemas, transforms, or another volatile value are rejected. Configuration files store ordinary values; `simplify()` unwraps references. Serialized schemas preserve their field types, defaults, roles, and volatile marker for schema-driven forms. Existing settings consumers continue to use their own settings interfaces. + ## Computed config values The loader used in this repo supports a `!!js` tag for config values that must be computed at load time: diff --git a/docs/cordis-tutorial/05-config.zh.md b/docs/cordis-tutorial/05-config.zh.md index e19dcb3ab0..65e9ea73a5 100644 --- a/docs/cordis-tutorial/05-config.zh.md +++ b/docs/cordis-tutorial/05-config.zh.md @@ -67,6 +67,33 @@ ValidationError: invalid config: 插件的 fiber 进入 FAILED 状态,本教程的启动器打印错误后以状态码 1 退出。如果某个插件的配置通过了 schema 验证,但其中指定的资源或提供方不可用,该插件也应当在能解析该引用时立即拒绝。 + +## Volatile 字段 + +对于插件在每次操作中读取的字段,可以使用 `.volatile()`。字段变化会更新稳定引用,无需重新挂载插件。通过 `.get()` 读取: + +```ts +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/cordis-plugin-loader' +import Schema from '@deepseek-ai/schemastery' + +export const Config = Schema.object({ + greeting: Schema.string().default('Hello').volatile(), +}) + +export function apply(ctx: Context, config: ReturnType) { + ctx.on('loader/volatile-update', () => { + console.log(config.greeting.get()) + }) +} +``` + +直接调用 `Config(raw)` 也会返回引用。没有默认值的可选字段仍然具有引用;字段缺省时,`.get()` 返回 `undefined`。可以保存引用,也可以在单次操作中保存读取值,包括跨越 `await`,但不能将该值用于后续操作。对象和数组值是脱离输入、递归冻结的普通数据快照;函数、类实例和循环引用会被拒绝。 + +Loader 比较原始配置时忽略 schema 声明的 volatile 字段。仅 volatile 变化会经目标插件的 `internal/config` 钩子解析并校验;当所有普通字段的有效值仍然一致时,Loader 把新值提交到运行中的引用,并向所属实例发出一次 `loader/volatile-update`,参数是以键数组表示的变化路径,不进入目标插件的 `internal/update`。等值更新不通知。无效候选会记录日志,运行中的引用保持不变,直到下次激活。普通字段有效值变化(包括表达式求值结果变化)以及普通字段同时变化时沿用原更新流程,旧引用不更新也不接收通知。Group/Include 仍分发子条目更新。直接 `fiber.update()`、代码替换和依赖替换保留原有生命周期;`noSave` 仍控制直接更新的持久化。通知使用普通 `emit`,不等待资源重新配置完成。 + +在固定对象路径上声明 volatile 字段,或将整个对象、数组标记为 volatile。数组、字典、union 或 intersect 分支、lazy、transform 或另一个 volatile 值内部的独立引用会被拒绝。配置文件保存普通值;`simplify()` 会解包引用。序列化 schema 保留字段类型、默认值、角色和 volatile 标记,供基于 schema 的表单使用。现有 settings 消费者继续使用原有 settings 接口。 + ## 计算得到的配置值 本仓库使用的 loader 支持 `!!js` 标签,用于必须在加载时计算的配置值: diff --git a/packages/boot/app-boot/README.i18n.yaml b/packages/boot/app-boot/README.i18n.yaml index 75f348ee55..a8617d5fc1 100644 --- a/packages/boot/app-boot/README.i18n.yaml +++ b/packages/boot/app-boot/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/boot/app-boot/README.md -README.md: ef98b3fd98829c14dc6614de321cc02837c8eb0c -README.zh.md: 2e0ce42936701ddd94d82dae5fcfee5d33e326e0 +README.md: 4763d5e0e22560373320b1f6a478e3a71212c4e6 +README.zh.md: 5fc90e3773ce152e8fca78c101753e746e986985 diff --git a/packages/boot/app-boot/README.md b/packages/boot/app-boot/README.md index ef98b3fd98..4763d5e0e2 100644 --- a/packages/boot/app-boot/README.md +++ b/packages/boot/app-boot/README.md @@ -73,7 +73,7 @@ Use `readPluginMeta(specifier, parentURL)` or `ctx.pluginPackages.metaOf(specifi ### Startup and reload failures -Profile reconciliation returns diagnostics for unchanged inactive entries without failing an unrelated mutation. A new inactive entry, a changed configuration or fiber, or a changed diagnostic fails reconciliation; removed fibers must still finish disposal. Explicit enablement targets must activate even when their failure predates the operation. +Profile reconciliation returns diagnostics for unchanged inactive entries without failing an unrelated mutation. A new inactive entry, a changed configuration or fiber, or a changed diagnostic fails reconciliation; removed fibers must still finish disposal. Explicit enablement targets must activate even when their failure predates the operation. Successful reconciliation returns after lifecycle settlement and diagnostic checks; volatile-only entry changes are committed by Loader during the update. After the Loader settles, app-boot warns when only optional entries are inactive. If an enabled required entry cannot activate, `boot()` rejects with `StartupError` after disposal. An independently owned logger exporter retains warning and error records through asynchronous disposal and is released before `boot()` settles. Its message groups all failed plugins and pending services, marks required entries, and retains original stacks, nested causes, and aggregate members. The CLI prints that message once and saves [full startup diagnostics](../../../apps/cli/reference/README.md#startup-diagnostics) before exiting with code 1; unrelated exceptions retain their normal stack output. In the table, stopping startup means disposing any mounted plugins and exiting nonzero without reporting readiness; continuing keeps successful plugins running. Later configuration HMR does not repeat the required-startup audit and does not roll back the whole update. diff --git a/packages/boot/app-boot/README.zh.md b/packages/boot/app-boot/README.zh.md index 2e0ce42936..5fc90e3773 100644 --- a/packages/boot/app-boot/README.zh.md +++ b/packages/boot/app-boot/README.zh.md @@ -73,7 +73,7 @@ profile 是同一套 dsh 安装提供不同应用界面的方式:`web`、`head ### 启动与重载失败 -profile 重载返回未变化的已有故障诊断,不让无关修改因此失败。新增未激活条目、配置或 fiber 变化、诊断变化都会使重载失败;被移除的 fiber 仍须完成释放。显式启用的目标必须成功激活,即使它的故障早于本次操作。 +profile 重载返回未变化的已有故障诊断,不让无关修改因此失败。新增未激活条目、配置或 fiber 变化、诊断变化都会使重载失败;被移除的 fiber 仍须完成释放。显式启用的目标必须成功激活,即使它的故障早于本次操作。 成功重载在生命周期结束及诊断检查通过后返回;仅 volatile 的条目变化由 Loader 在更新过程中提交。 Loader 结算后,app-boot 在仅 optional 条目未激活时输出警告。如果已启用的 required 条目无法激活,`boot()` 会在释放资源后以 `StartupError` 拒绝。独立管理生命周期的 logger exporter 会保留异步资源释放期间的警告和错误记录,并在 `boot()` 结算前释放。其消息分组列出所有失败插件和等待的服务,标记 required 条目,并保留原始堆栈、嵌套原因和聚合错误成员。CLI 仅输出该消息一次,并在保存[完整启动诊断](../../../apps/cli/reference/README.zh.md#startup-diagnostics)后以退出码 1 结束;其他异常保留正常堆栈输出。表中的“终止启动”指释放已挂载插件并以非零码退出,不报告就绪;“继续”指保留成功运行的插件。后续配置 HMR 不会再次执行 required 启动审计,也不会回滚整个更新。 diff --git a/packages/boot/hmr/README.i18n.yaml b/packages/boot/hmr/README.i18n.yaml index bb50a0f843..2a8a9c45e5 100644 --- a/packages/boot/hmr/README.i18n.yaml +++ b/packages/boot/hmr/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/boot/hmr/README.md -README.md: 735b37c41e50c6a1f663cbfa0cde42f7250ec415 -README.zh.md: b0d3196913cb11e434b397350c81ad1bb45dc0c6 +README.md: 9e2c62c739c420ceae3db3fd5ade58d6eeadacec +README.zh.md: fa926d5998f7f4b784fe2f848b5acc3047b91b77 diff --git a/packages/boot/hmr/README.md b/packages/boot/hmr/README.md index 735b37c41e..9e2c62c739 100644 --- a/packages/boot/hmr/README.md +++ b/packages/boot/hmr/README.md @@ -54,7 +54,7 @@ Chokidar options, including polling, retain their existing meaning. Exact config
Implementation internals — click to expand -`watchConfig()` registers an awaited configuration handler. `runExclusive()` serializes configuration changes and Loader updates with automatic reloads and rejects nested transactions. Package installation and removal run outside this queue. HMR does not acquire the package writer lock; manifest notifications reload only when the ordered `dsh.profile.bundles` list changes. Profile and home patch changes also trigger recomposition. File events received during a configuration transaction are processed afterward. +`watchConfig()` registers an awaited configuration handler. `runExclusive()` serializes configuration changes and Loader updates with automatic reloads and rejects nested transactions. Package installation and removal run outside this queue. HMR does not acquire the package writer lock; manifest notifications reload only when the ordered `dsh.profile.bundles` list changes. Profile and home patch changes also trigger recomposition. File events received during a configuration transaction are processed afterward. Include refreshes and profile reconciliation reach plugins through ordinary Loader entry updates; Loader commits volatile-only changes in place. App-boot owns profile parsing and patch precedence. HMR reads the launcher’s data-only `profileContext`, registers the profile manifest and both user patch watches during initialization, and waits for application readiness before processing changes. Its disposal closes the watchers and cancels reloads waiting for startup. HMR also owns module-cache replacement and reload scheduling. Configuration watchers start outside the active transaction context so later notifications can enter the queue. No invariant companion is published because the queue and watcher registrations have no independent persisted projection. diff --git a/packages/boot/hmr/README.zh.md b/packages/boot/hmr/README.zh.md index b0d3196913..fa926d5998 100644 --- a/packages/boot/hmr/README.zh.md +++ b/packages/boot/hmr/README.zh.md @@ -54,7 +54,7 @@ Chokidar 选项(包括轮询)保持原有含义。精确配置监听同时
实现细节——点击展开 -`watchConfig()` 注册会被等待的配置处理器。`runExclusive()` 将配置变更、Loader 更新与自动重载串行化,并拒绝嵌套事务。包安装和删除在该队列之外执行。HMR 不获取包操作写锁;manifest 通知仅在有序的 `dsh.profile.bundles` 列表变化时触发重载。profile 与 home patch 变化也会触发重新组合。配置事务期间收到的文件事件在事务结束后处理。 +`watchConfig()` 注册会被等待的配置处理器。`runExclusive()` 将配置变更、Loader 更新与自动重载串行化,并拒绝嵌套事务。包安装和删除在该队列之外执行。HMR 不获取包操作写锁;manifest 通知仅在有序的 `dsh.profile.bundles` 列表变化时触发重载。profile 与 home patch 变化也会触发重新组合。配置事务期间收到的文件事件在事务结束后处理。 Include 刷新和 profile 重载都通过普通的 Loader 条目更新到达插件;仅 volatile 变化由 Loader 就地提交。 App-boot 负责 profile 解析和 patch 优先级规则。HMR 读取启动器提供的纯数据 `profileContext`,在初始化时注册 profile manifest 和两份用户 patch 的监听,并等待应用就绪后处理更改。销毁 HMR 时会关闭监听器并取消等待启动的重载。HMR 也负责模块缓存替换和重载调度。配置监听器在当前事务上下文之外启动,使后续通知可以进入队列。不发布 invariant 伴生入口,因为队列和监听注册没有独立的持久投影。 diff --git a/packages/boot/hmr/tests/modules.spec.ts b/packages/boot/hmr/tests/modules.spec.ts index 6e2a7e12a9..93b96a007c 100644 --- a/packages/boot/hmr/tests/modules.spec.ts +++ b/packages/boot/hmr/tests/modules.spec.ts @@ -7,6 +7,7 @@ import NodeModule, { createRequire } from 'node:module' import { Context, type Plugin } from '@deepseek-ai/cordis' import Loader, { type ModuleJob, type ModuleLoader } from '@deepseek-ai/cordis-plugin-loader' import Timer from '@deepseek-ai/cordis-plugin-timer' +import z from '@deepseek-ai/schemastery' import { expect, it, onTestFinished, vi } from 'vitest' import Hmr from '../src/index.ts' @@ -87,6 +88,31 @@ it.each(['v1', 'v2'] as const)('replaces a %s module and retains the latest Load expect(mounted.at(-1)).toBe('after:next') }) +it('replaces volatile references on code HMR after an in-place config update', async () => { + const { ctx, module, imports, reload } = await fixture() + const Config = z.object({ value: z.string().volatile() }) + const configs: ReturnType[] = [] + const before = { Config, apply(_ctx: Context, config: ReturnType) { configs.push(config) } } + const after = { Config, apply(_ctx: Context, config: ReturnType) { configs.push(config) } } + const job = module('volatile.mjs', before) + const entry = ctx.loader.resolve(await ctx.loader.create({ name: job.url, config: { value: 'initial' } })) + await ctx.loader.await() + await entry.update({ config: { value: 'current' } }) + await ctx.loader.await() + expect(configs).toHaveLength(1) + const old = configs[0]!.value + expect(old.get()).toBe('current') + imports.set(job.url, after) + reload.stashed.add(job.url) + await reload.partialReload() + expect(configs).toHaveLength(2) + expect(configs[1]!.value).not.toBe(old) + expect(configs[1]!.value.get()).toBe('current') + await entry.update({ config: { value: 'after-reload' } }) + expect(configs[1]!.value.get()).toBe('after-reload') + expect(old.get()).toBe('current') +}) + it('reactivates a source-replaced consumer after provider and consumer configuration changes', async () => { const { ctx, module, imports, reload } = await fixture() const mounted: string[] = [] diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5d3e3cf6f4..39acefeee7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -12990,6 +12990,9 @@ importers: '@deepseek-ai/cosmokit': specifier: link:../cosmokit version: link:../cosmokit + '@deepseek-ai/schemastery': + specifier: link:../schemastery + version: link:../schemastery node-addon-require-builtin: specifier: ^0.1.6 version: 0.1.6 diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 1b19d386b1..b742bbcc58 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -895,19 +895,21 @@ export const CORDIS_CATALOG_POLICY: CordisCatalogPolicy = { ], }], inheritedEvents: [ - { name: 'internal/plugin', summary: 'A plugin fiber was created.', source: 'vendor/cordis/src/events.ts:328' }, - { name: 'internal/status', summary: 'A fiber changed lifecycle state.', source: 'vendor/cordis/src/events.ts:330' }, - { name: 'internal/service', summary: 'Interception hook for a service binding (no core producer).', source: 'vendor/cordis/src/events.ts:332' }, - { name: 'internal/update', summary: 'Waterfall: a fiber config update is being applied.', source: 'vendor/cordis/src/events.ts:334' }, - { name: 'internal/get', summary: 'Waterfall: a service is being read from the store.', source: 'vendor/cordis/src/events.ts:336' }, - { name: 'internal/set', summary: 'Waterfall: a service is being written to the store.', source: 'vendor/cordis/src/events.ts:338' }, - { name: 'internal/listener', summary: 'A listener was registered.', source: 'vendor/cordis/src/events.ts:340' }, - { name: 'internal/dispatch', summary: 'An event is being dispatched to listeners.', source: 'vendor/cordis/src/events.ts:342' }, - { name: 'exit', summary: 'The process is exiting on a signal.', source: 'vendor/loader/src/index.ts:23' }, - { name: 'loader/config-update', summary: 'The loader config tree changed.', source: 'vendor/loader/src/index.ts:24' }, - { name: 'loader/entry-init', summary: 'A config entry is being initialized.', source: 'vendor/loader/src/index.ts:25' }, - { name: 'loader/partial-dispose', summary: 'An entry is being partially disposed on reload.', source: 'vendor/loader/src/index.ts:26' }, - { name: 'loader/patch-context', summary: 'A context is being patched during a reload.', source: 'vendor/loader/src/index.ts:27' }, + { name: 'internal/plugin', summary: 'A plugin fiber was created.', source: 'vendor/cordis/src/events.ts:331' }, + { name: 'internal/status', summary: 'A fiber changed lifecycle state.', source: 'vendor/cordis/src/events.ts:333' }, + { name: 'internal/service', summary: 'Interception hook for a service binding (no core producer).', source: 'vendor/cordis/src/events.ts:341' }, + { name: 'internal/update', summary: 'Waterfall: a fiber config update is being applied.', source: 'vendor/cordis/src/events.ts:343' }, + { name: 'internal/config', summary: 'Waterfall: a fiber config is being resolved before validation.', source: 'vendor/cordis/src/events.ts:339' }, + { name: 'internal/get', summary: 'Waterfall: a service is being read from the store.', source: 'vendor/cordis/src/events.ts:345' }, + { name: 'internal/set', summary: 'Waterfall: a service is being written to the store.', source: 'vendor/cordis/src/events.ts:347' }, + { name: 'internal/listener', summary: 'A listener was registered.', source: 'vendor/cordis/src/events.ts:349' }, + { name: 'internal/dispatch', summary: 'An event is being dispatched to listeners.', source: 'vendor/cordis/src/events.ts:351' }, + { name: 'exit', summary: 'The process is exiting on a signal.', source: 'vendor/loader/src/index.ts:25' }, + { name: 'loader/config-update', summary: 'The loader config tree changed.', source: 'vendor/loader/src/index.ts:26' }, + { name: 'loader/entry-init', summary: 'A config entry is being initialized.', source: 'vendor/loader/src/index.ts:27' }, + { name: 'loader/partial-dispose', summary: 'An entry is being partially disposed on reload.', source: 'vendor/loader/src/index.ts:28' }, + { name: 'loader/patch-context', summary: 'A context is being patched during a reload.', source: 'vendor/loader/src/index.ts:41' }, + { name: 'loader/volatile-update', summary: 'Volatile config values committed into the running fiber without a remount; dispatched to the owning fiber only.', source: 'vendor/loader/src/index.ts:34' }, ], inheritedServices: [ { name: 'ctx.on / ctx.once', summary: 'Register an event listener (disposable).', source: 'vendor/cordis/src/events.ts:34' }, diff --git a/scripts/loader-config-diff.spec.ts b/scripts/loader-config-diff.spec.ts new file mode 100644 index 0000000000..0cd0a3eb50 --- /dev/null +++ b/scripts/loader-config-diff.spec.ts @@ -0,0 +1,109 @@ +/** Raw config comparison reads schema metadata without resolving config or committing references. */ +import { expect, it, vi } from 'vitest' +import z from '@deepseek-ai/schemastery' +import { equalExceptVolatile as equal } from '../vendor/loader/src/config/diff.ts' + +it('ignores volatile fields in frozen raw inputs without running schema callbacks', () => { + const validate = vi.fn((value: string) => value.trim()) + const schema = z.object({ title: z.transform(z.string(), validate).volatile(), fixed: z.string() }) + Object.freeze(schema.meta) + Object.freeze(schema.dict) + const previous = Object.freeze({ title: 'old', fixed: 'same' }) + const next = Object.freeze({ title: { __jsExpr: 'throw new Error("must not run")' }, fixed: 'same' }) + expect(equal(previous, next, schema)).toBe(true) + expect(equal(previous, next, schema)).toBe(true) + expect(validate).not.toHaveBeenCalled() + expect(previous.title).toBe('old') + expect(next.title).toEqual({ __jsExpr: 'throw new Error("must not run")' }) +}) + +it('ignores absent, nested and whole-object/array/union volatile fields', () => { + const schema = z.object({ + nested: z.object({ value: z.string().volatile() }), + block: z.object({ title: z.string() }).volatile(), + list: z.array(z.string()).volatile(), + choice: z.union([z.string(), z.number()]).volatile(), + }) + const next = { nested: { value: 'new' }, block: { title: 'new' }, list: ['new'], choice: 1 } + expect(equal({}, next, schema)).toBe(true) + expect(equal(next, {}, schema)).toBe(true) + expect(equal('old', 'new', z.string().volatile())).toBe(true) + const restored = new z(JSON.parse(JSON.stringify(schema)) as z) + expect(equal({}, next, restored)).toBe(true) +}) + +it('preserves ordinary and unknown fields, object defaults and parent expressions', () => { + const schema = z.object({ nested: z.object({ live: z.string().volatile(), fixed: z.string() }).default({ fixed: 'default' }) }) + expect(equal({}, { nested: { live: 'new', fixed: 'default' } }, schema)).toBe(true) + expect(equal({}, { nested: { live: 'new' } }, schema)).toBe(false) + expect(equal({}, { unknown: 'new' }, schema)).toBe(false) + expect(equal({ nested: { __jsExpr: 'source.a' } }, { nested: { __jsExpr: 'source.b' } }, schema)).toBe(false) + expect(equal({ nested: 'invalid' }, { nested: { live: 'new' } }, schema)).toBe(false) + expect(equal({ nested: new Date(0) }, { nested: new Date(1) }, schema)).toBe(false) + expect(equal({ nested: [] }, { nested: ['new'] }, schema)).toBe(false) +}) + +it('keeps ordinary raw changes even if schema validation would normalize them to equal values', () => { + const normalize = vi.fn(() => 'same') + const schema = z.object({ fixed: z.transform(z.string(), normalize), live: z.string().volatile() }) + expect(equal({ fixed: 'first' }, { fixed: 'second' }, schema)).toBe(false) + expect(normalize).not.toHaveBeenCalled() + const other = { '~standard': { version: 1 as const, vendor: 'other', validate: vi.fn() } } + expect(equal('first', 'second', other)).toBe(false) + expect(other['~standard'].validate).not.toHaveBeenCalled() + expect(equal('first', 'second', undefined)).toBe(false) +}) + +it('compares raw values strictly without a schema', () => { + expect(equal([undefined], [null], undefined)).toBe(false) + expect(equal(undefined, null, undefined)).toBe(false) + expect(equal({ fixed: 'same' }, { fixed: 'same' }, undefined)).toBe(true) + expect(equal({ list: Array(1) }, { list: ['new'] }, undefined)).toBe(false) +}) + +it('compares recursive schemas conservatively and visits shared schema nodes at each path', () => { + const recursive = z.object({ value: z.string() }).extra('default', undefined) + recursive.set('child', recursive) + expect(equal({ value: 'old' }, { value: 'new' }, recursive)).toBe(false) + const shared = z.object({ value: z.string().volatile() }) + const schema = z.object({ first: shared, second: shared }) + expect(equal({}, { first: { value: 'one' }, second: { value: 'two' } }, schema)).toBe(true) +}) + +it('equates absent objects with defaults while preserving ordinary field differences', () => { + const schema = z.object({ nested: z.object({ fixed: z.string() }).default({ fixed: 'default' }) }) + for (const absent of [undefined, null]) { + expect(equal(absent, {}, schema)).toBe(true) + expect(equal({}, absent, schema)).toBe(true) + expect(equal({ nested: absent }, { nested: { fixed: 'default' } }, schema)).toBe(true) + } + expect(equal({}, { nested: { fixed: 'changed' } }, schema)).toBe(false) + expect(equal({}, { nested: {} }, schema)).toBe(false) +}) + +it('preserves parent expression edits even when their marker matches a volatile field', () => { + const schema = z.object({ __jsExpr: z.string().volatile() }) + expect(equal({ __jsExpr: 'first' }, { __jsExpr: 'second' }, schema)).toBe(false) +}) + +it('detects ordinary sparse array edits in both directions', () => { + const schema = z.object({ list: z.array(z.string()), live: z.string().volatile() }) + const before = { list: Array(1), live: 'before' } + const after = { list: ['new'], live: 'after' } + expect(equal(before, after, schema)).toBe(false) + expect(equal(after, before, schema)).toBe(false) +}) + +it('compares unknown fields whose names match Object prototype properties', () => { + const schema = z.object({ live: z.string().volatile() }) + for (const key of ['constructor', 'toString', '__proto__']) { + const previous = { [key]: 'first', live: 'old' } + expect(equal(previous, { [key]: 'second', live: 'new' }, schema)).toBe(false) + expect(equal(previous, { [key]: 'first', live: 'new' }, schema)).toBe(true) + } +}) + +it('compares metadata-free serialized schema nodes', () => { + const schema = new z(JSON.parse('{"type":"object","dict":{"nested":{"type":"object","dict":{"enabled":{"type":"boolean"}}}}}') as z) + expect(equal({ nested: { enabled: true } }, { nested: { enabled: false } }, schema)).toBe(false) +}) diff --git a/scripts/loader-volatile-update.spec.ts b/scripts/loader-volatile-update.spec.ts new file mode 100644 index 0000000000..16d8f3b0a8 --- /dev/null +++ b/scripts/loader-volatile-update.spec.ts @@ -0,0 +1,634 @@ +/** Loader commits volatile config values into running fibers without remounting; ordinary changes keep the update lifecycle. */ +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { describe, expect, it, onTestFinished, vi } from 'vitest' +import { Context, type Fiber, type Plugin } from '@deepseek-ai/cordis' +import Loader, { Group } from '@deepseek-ai/cordis-plugin-loader' +import Include from '@deepseek-ai/cordis-plugin-include' +import Timer from '@deepseek-ai/cordis-plugin-timer' +import z from '@deepseek-ai/schemastery' +import { Config } from './volatile-config.fixture.ts' +import Hmr from '@deepseek-ai/dsh-hmr' +import { boot, reconcileProfilePatches } from '@deepseek-ai/dsh-app-boot' + +function context() { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + return ctx +} + +async function runtimeContext() { + const ctx = context() + await ctx.plugin(Loader) + return ctx +} + +async function mountEntry(ctx: Context, plugin: Plugin, config: unknown = {}): Promise { + const name = `consumer-${Object.keys(ctx.loader.builtins).length}` + ctx.loader.builtins[name] = plugin + const id = await ctx.loader.create({ name: `cordis:${name}`, config }) + const fiber = ctx.loader.resolve(id).fiber! + await fiber.await() + return fiber +} + +async function update(fiber: Fiber, config: unknown): Promise { + await fiber.entry!.update({ config }) + await fiber.await() +} + +describe('volatile Loader updates', () => { + it('updates a whole-config reference and reports the root path', async () => { + const ctx = await runtimeContext() + const Config = z.object({ title: z.string() }).volatile() + const events = vi.fn() + const fiber = await mountEntry(ctx, { Config, apply(owner: Context) { + owner.on('loader/volatile-update', events) + } }, { title: 'first' }) + const reference = fiber.config as ReturnType + await update(fiber, { title: 'second' }) + expect(fiber.config).toBe(reference) + expect(reference.get()).toEqual({ title: 'second' }) + expect(events).toHaveBeenCalledExactlyOnceWith([[]]) + }) + it('commits all references before one local event without remounting', async () => { + const ctx = await runtimeContext() + const configs: ReturnType[] = [] + const observed: unknown[] = [] + const mount = vi.fn(function (owner: Context, config: ReturnType) { + configs.push(config) + owner.on('loader/volatile-update', paths => observed.push({ paths, title: config.title.get(), count: config.nested.count.get() })) + }) + const first = await mountEntry(ctx, { Config, apply: mount }, {}) + await mountEntry(ctx, { Config, apply: mount }, {}) + const initial = configs[0]! + const title = initial.title + await update(first, { title: 'hello' }) + expect(observed).toEqual([]) + await update(first, { title: 'next', nested: { count: 2 } }) + await first.await() + expect(mount).toHaveBeenCalledTimes(2) + expect(first.config).toBe(initial) + expect(initial.title).toBe(title) + expect(configs[1]!.title.get()).toBe('hello') + expect(observed).toEqual([{ paths: [['title'], ['nested', 'count']], title: 'next', count: 2 }]) + await update(first, { title: 'next', nested: { count: 2 } }) + expect(observed).toHaveLength(1) + await update(first, { optional: 'added' }) + expect(initial.optional.get()).toBe('added') + await update(first, {}) + expect(initial.optional.get()).toBeUndefined() + }) + + it('keeps references on invalid updates and replaces them on mixed updates', async () => { + const ctx = await runtimeContext() + const notifications = vi.fn() + const disposed = vi.fn() + const configs: ReturnType[] = [] + const plugin = { Config, apply(owner: Context, config: ReturnType) { + configs.push(config) + owner.on('loader/volatile-update', notifications) + owner.effect(() => disposed) + } } + const fiber = await mountEntry(ctx, plugin, {}) + const before = configs[0]! + await update(fiber, { title: 'invalid candidate', nested: { count: -1 } }) + expect(before.title.get()).toBe('hello') + expect(notifications).not.toHaveBeenCalled() + await update(fiber, { title: 'new', fixed: 'restart' }) + await fiber.await() + expect(configs).toHaveLength(2) + expect(disposed).toHaveBeenCalledOnce() + expect(notifications).not.toHaveBeenCalled() + expect(before.title.get()).toBe('hello') + expect(configs[1]!.title.get()).toBe('new') + expect(configs[1]!.title).not.toBe(before.title) + }) + + it('bypasses custom update hooks for volatile changes and retains them for mixed changes', async () => { + const ctx = await runtimeContext() + const hooks: string[] = [] + const globalHook = vi.fn((_config: unknown, _noSave: boolean, next: () => void) => { next() }) + ctx.on('internal/update', globalHook, { global: true }) + const fiber = await mountEntry(ctx, { Config, apply(owner: Context) { + owner.on('internal/update', (config: ReturnType) => { + hooks.push(config.title.get()) + }) + } }, {}) + const initial = fiber.config as ReturnType + await update(fiber, { title: 'accepted' }) + expect(fiber.config).toBe(initial) + expect(initial.title.get()).toBe('accepted') + await update(fiber, { title: 'accepted' }) + expect(hooks).toEqual([]) + expect(globalHook).not.toHaveBeenCalled() + await update(fiber, { title: 'custom', fixed: 'changed' }) + expect(hooks).toEqual(['custom']) + expect(initial.title.get()).toBe('accepted') + }) + + it('compares ordinary dates and arrays and retains the existing nonvolatile restart behavior', async () => { + const ctx = await runtimeContext() + const schema = z.object({ live: z.string().volatile(), date: z.date(), list: z.array(z.string()) }) + const apply = vi.fn(function () {}) + const fiber = await mountEntry(ctx, { Config: schema, apply }, { live: 'a', date: '2026-01-01', list: ['a'] }) + await update(fiber, { live: 'b', date: '2026-01-01', list: ['a'] }) + await fiber.await() + expect(apply).toHaveBeenCalledOnce() + await update(fiber, { live: 'c', date: '2026-01-02', list: ['a'] }) + await fiber.await() + expect(apply).toHaveBeenCalledTimes(2) + await update(fiber, { live: 'd', date: '2026-01-02', list: ['b'] }) + await fiber.await() + expect(apply).toHaveBeenCalledTimes(3) + const ordinary = await mountEntry(ctx, { Config: z.object({ value: z.string() }), apply() { apply() } }, { value: 'same' }) + ordinary.update({ value: 'same' }) + await ordinary.await() + expect(apply).toHaveBeenCalledTimes(5) + }) + + it('resolves pending updates and creates fresh references after dependency replacement', async () => { + const ctx = await runtimeContext() + const configs: ReturnType[] = [] + const consumer = await mountEntry(ctx, { Config, inject: ['volatile-test-provider'], apply(_ctx: Context, config: ReturnType) { + configs.push(config) + } }, {}) + await update(consumer, { title: 'pending' }) + const provider = await ctx.plugin({ apply(owner: Context) { owner.provide('volatile-test-provider', {}) } }) + await consumer.await() + expect(configs[0]!.title.get()).toBe('pending') + await update(consumer, { title: 'live' }) + await provider.dispose() + const before = configs[0]!.title + await ctx.plugin({ apply(owner: Context) { owner.provide('volatile-test-provider', {}) } }) + await consumer.await() + expect(configs).toHaveLength(2) + expect(configs[1]!.title.get()).toBe('live') + expect(configs[1]!.title).not.toBe(before) + }) + + it('remounts for changed class instances and cyclic ordinary config', async () => { + const ctx = await runtimeContext() + const schema = z.object({ + live: z.string().volatile(), + url: z.transform(z.string(), value => new URL(value)), + data: z.transform(z.string(), () => { const data: Record = {}; data.self = data; return data }), + }) + const apply = vi.fn(function () {}) + const oldUrl = 'https://a.example/' + const newUrl = 'https://b.example/' + const fiber = await mountEntry(ctx, { Config: schema, apply }, { live: 'a', url: oldUrl }) + const before = fiber.config as ReturnType + await update(fiber, { live: 'b', url: newUrl }) + await fiber.await() + expect(apply).toHaveBeenCalledTimes(2) + expect((fiber.config as ReturnType).url.href).toBe(newUrl) + expect(before.live.get()).toBe('a') + await update(fiber, { live: 'c', url: newUrl, data: 'first' }) + await update(fiber, { live: 'd', url: newUrl, data: 'second' }) + expect(apply).toHaveBeenCalledTimes(4) + }) + + it('distinguishes undefined from null inside volatile arrays', async () => { + const ctx = await runtimeContext() + const schema = z.object({ values: z.array(z.any()).volatile() }) + const events = vi.fn() + const fiber = await mountEntry(ctx, { Config: schema, apply(owner: Context) { + owner.on('loader/volatile-update', events) + } }, { values: [undefined] }) + await update(fiber, { values: [null] }) + expect((fiber.config as ReturnType).values.get()).toEqual([null]) + expect(events).toHaveBeenCalledExactlyOnceWith([['values']]) + }) +}) + +it('reloads real YAML and persists plain values independently of custom update hooks', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-volatile-')) + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose(); await rm(root, { recursive: true, force: true }) }) + ctx.baseUrl = pathToFileURL(root).href + '/' + await ctx.plugin(Loader) + const configs: ReturnType[] = [] + ctx.loader.builtins.include = Include + ctx.loader.builtins.group = Group + const updates = vi.fn() + const consumer = { Config, apply(owner: Context, config: ReturnType) { + configs.push(config) + owner.on('internal/update', updates) + } } + ctx.loader.builtins['volatile-test'] = consumer + const filename = join(root, 'cordis.yml') + await writeFile(filename, '- id: group\n name: cordis:group\n group: true\n config:\n - id: consumer\n name: cordis:volatile-test\n config:\n title: initial\n') + const rootId = await ctx.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(filename).href } }) + await ctx.loader.await() + const include = ctx.loader.resolve(rootId).subtree as Include + const group = include.store.group!.fiber! + const groupUid = group.uid + const entry = [...ctx.loader.entries()].find(entry => entry.options.id === 'consumer')! + expect(configs[0]!.title.get()).toBe('initial') + await ctx.plugin(Timer) + // An exact-file config watch mirrors the HMR root-watch Include path, which packages/boot/hmr covers with a mocked watcher. + await ctx.plugin(Hmr, { root: [], ignored: [], debounce: 0 }) + const stopWatching = await ctx.hmr.watchConfig(filename, async () => { + await include.refresh() + await ctx.loader.await() + }) + await writeFile(filename, '- id: group\n name: cordis:group\n group: true\n config:\n - id: consumer\n name: cordis:volatile-test\n config:\n title: file-update\n') + // The config watcher stabilizes writes for two seconds before publishing a change. + await vi.waitFor(() => { expect(configs[0]!.title.get()).toBe('file-update') }, { timeout: 10_000 }) + await stopWatching() + expect(configs).toHaveLength(1) + expect(include.store.group!.fiber).toBe(group) + expect(group.uid).toBe(groupUid) + expect(configs[0]!.title.get()).toBe('file-update') + entry.fiber!.update({ title: 'program-update', group: { list: ['item'] } }) + expect(entry.options.config).toEqual({ title: 'program-update', group: { list: ['item'] } }) + entry.fiber!.update({ title: 'ephemeral' }, true) + expect(entry.options.config).toEqual({ title: 'program-update', group: { list: ['item'] } }) + await ctx.fiber.dispose() + const saved = await readFile(filename, 'utf8') + expect(saved).toContain('program-update') + expect(saved).not.toContain('get:') + expect(saved).not.toContain('ephemeral') + expect(updates).toHaveBeenCalledTimes(2) + const restored = context() + restored.baseUrl = ctx.baseUrl + await restored.plugin(Loader) + restored.loader.builtins.include = Include + restored.loader.builtins.group = Group + restored.loader.builtins['volatile-test'] = consumer + await restored.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(filename).href } }) + await restored.loader.await() + expect(configs).toHaveLength(2) + expect(configs[1]!.title.get()).toBe('program-update') + expect(configs[1]!.group.get()).toEqual({ list: ['item'] }) + await restored.fiber.dispose() +}) + +it('updates volatile children through Group and Include custom updates and saves ordinary config', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-volatile-tree-')) + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose(); await rm(root, { recursive: true, force: true }) }) + ctx.baseUrl = pathToFileURL(root).href + '/' + await ctx.plugin(Loader) + ctx.loader.builtins.include = Include + ctx.loader.builtins.group = Group + const configs: ReturnType[] = [] + const notifications = vi.fn() + const childUpdates = vi.fn() + ctx.loader.builtins['volatile-test'] = { Config, apply(owner: Context, config: ReturnType) { + configs.push(config) + owner.on('loader/volatile-update', notifications) + owner.on('internal/update', childUpdates) + } } + const child = (title: string) => ({ id: 'consumer', name: 'cordis:volatile-test', config: { title } }) + const filename = join(root, 'tree.json') + const includePath = pathToFileURL(filename).href + await writeFile(filename, JSON.stringify([{ id: 'group', name: 'cordis:group', group: true, config: [child('initial')] }])) + const rootId = await ctx.loader.create({ name: 'cordis:include', config: { path: includePath } }) + await ctx.loader.await() + const includeEntry = ctx.loader.resolve(rootId) + const include = includeEntry.subtree as Include + const group = include.store.group! + const consumer = include.store.consumer! + const originalInclude = includeEntry.fiber + const originalGroup = group.fiber + const originalConsumer = consumer.fiber + const initial = configs[0]! + + group.fiber!.update([child('group-update')]) + await ctx.loader.await() + expect(initial.title.get()).toBe('group-update') + expect(group.options.config).toEqual([child('group-update')]) + includeEntry.fiber!.update({ path: includePath, patches: [{ id: 'consumer', config: { title: 'include-update' } }] }) + await ctx.loader.await() + expect(initial.title.get()).toBe('include-update') + expect(includeEntry.fiber).toBe(originalInclude) + expect(group.fiber).toBe(originalGroup) + expect(consumer.fiber).toBe(originalConsumer) + expect(consumer.fiber!.config).toBe(initial) + expect(configs).toHaveLength(1) + expect(notifications).toHaveBeenCalledTimes(2) + expect(childUpdates).not.toHaveBeenCalled() + + const ordinary = await ctx.loader.create({ name: 'cordis:volatile-test', config: {} }) + const entry = ctx.loader.resolve(ordinary) + entry.fiber!.update({ title: 'custom-update', fixed: 'ordinary' }) + expect(childUpdates).toHaveBeenCalledOnce() + expect(entry.options.config).toEqual({ title: 'custom-update', fixed: 'ordinary' }) + expect((entry.fiber!.config as ReturnType).title.get()).toBe('hello') + entry.fiber!.update({ title: 'ephemeral', fixed: 'ordinary' }, true) + expect(childUpdates).toHaveBeenCalledTimes(2) + expect(entry.options.config).toEqual({ title: 'custom-update', fixed: 'ordinary' }) + expect(() => { entry.fiber!.update({ nested: { count: -1 } }) }).toThrow() + expect(childUpdates).toHaveBeenCalledTimes(2) + expect(entry.options.config).toEqual({ title: 'custom-update', fixed: 'ordinary' }) +}) + +it('commits volatile edits in place and retains direct Fiber updates', async () => { + const ctx = await runtimeContext() + const notifications = vi.fn() + const apply = vi.fn(function (owner: Context) { owner.on('loader/volatile-update', notifications) }) + const fiber = await mountEntry(ctx, { Config, apply }, {}) + const original = fiber.config as ReturnType + await ctx.loader.create({ name: 'cordis:disabled', disabled: true }) + await update(fiber, { title: 'enabled' }) + expect(apply).toHaveBeenCalledOnce() + expect(fiber.config).toBe(original) + expect(original.title.get()).toBe('enabled') + expect(notifications).toHaveBeenCalledExactlyOnceWith([['title']]) + await update(fiber, { title: 'invalid', nested: { count: -1 } }) + expect(original.title.get()).toBe('enabled') + await update(fiber, { title: 'mixed', fixed: 'changed' }) + expect(apply).toHaveBeenCalledTimes(2) + expect(original.title.get()).toBe('enabled') + const current = fiber.config as ReturnType + expect(current.title.get()).toBe('mixed') + + const hook = vi.fn((_config: unknown, _noSave: boolean, next: () => void) => { next() }) + fiber.ctx.on('internal/update', hook) + fiber.update({ title: 'direct' }) + await fiber.await() + expect(hook).toHaveBeenCalledOnce() + expect(apply).toHaveBeenCalledTimes(3) + expect(current.title.get()).toBe('mixed') + expect(notifications).toHaveBeenCalledOnce() +}) + +it('parses a volatile-only update through the config hook without patching the entry context', async () => { + const ctx = await runtimeContext() + const trace: string[] = [] + const trim = vi.fn((value: string) => { trace.push('validate'); return value.trim() }) + const Config = z.object({ block: z.object({ title: z.transform(z.string(), trim, true) }).volatile() }) + const fiber = await mountEntry(ctx, { Config, apply(owner: Context) { + owner.on('loader/volatile-update', () => { trace.push('notify') }) + } }, { block: { title: 'initial' } }) + const current = fiber.config as ReturnType + const resolveHook = vi.fn((_raw: unknown, next: () => unknown) => next()) + fiber.ctx.on('internal/config', resolveHook) + const contextPatch = vi.fn((_entry: unknown, next: () => void) => { next() }) + ctx.on('loader/patch-context', contextPatch) + trim.mockClear() + trace.length = 0 + const raw = { block: { title: ' changed ' } } + await fiber.entry!.update({ config: raw }) + expect(contextPatch).not.toHaveBeenCalled() + expect(trim).toHaveBeenCalledExactlyOnceWith(' changed ') + expect(resolveHook).toHaveBeenCalledOnce() + expect(trace).toEqual(['validate', 'notify']) + expect(current.block.get()).toEqual({ title: 'changed' }) + expect(fiber._config).toBe(raw) +}) + +it.each([true, false])('keeps old references untouched when isolation replaces a dependency (available: %s)', async (available) => { + const ctx = await runtimeContext() + const configs: ReturnType[] = [] + const notifications = vi.fn() + ctx.loader.builtins.provider = { apply(owner: Context) { owner.provide('volatile-isolated-service', {}) } } + ctx.loader.builtins.consumer = { + inject: ['volatile-isolated-service'], Config, + apply(owner: Context, config: ReturnType) { + configs.push(config) + owner.on('loader/volatile-update', notifications) + }, + } + const provider = (realm: string) => ctx.loader.create({ + name: 'cordis:provider', isolate: { 'volatile-isolated-service': realm }, + }) + await provider('a') + if (available) await provider('b') + const id = await ctx.loader.create({ + name: 'cordis:consumer', isolate: { 'volatile-isolated-service': 'a' }, config: { title: 'old' }, + }) + await ctx.loader.await() + const original = configs[0]! + await ctx.loader.resolve(id).update({ isolate: { 'volatile-isolated-service': 'b' }, config: { title: 'new' } }) + await ctx.loader.await() + expect(configs).toHaveLength(available ? 2 : 1) + expect(original.title.get()).toBe('old') + expect(notifications).not.toHaveBeenCalled() + if (!available) { + await provider('b') + await ctx.loader.await() + } + expect(configs).toHaveLength(2) + expect(configs[1]!.title.get()).toBe('new') +}) + +it.each(['group', 'include'] as const)('applies profile patches to a %s subtree without HMR and keeps mixed updates on the normal lifecycle', async (kind) => { + const root = await mkdtemp(join(tmpdir(), 'dsh-volatile-profile-')) + onTestFinished(() => rm(root, { recursive: true, force: true })) + const configs: ReturnType[] = [] + const events = vi.fn() + const dispose = vi.fn() + const consumer = { Config, apply(owner: Context, config: ReturnType) { + configs.push(config) + owner.on('loader/volatile-update', events) + owner.effect(() => dispose) + } } + const child = (title: string, fixed = 'fixed') => ({ id: 'consumer', name: 'cordis:consumer', config: { title, fixed } }) + const nested = join(root, 'nested.json') + await writeFile(nested, JSON.stringify([child('initial')])) + const carrierConfig = (title: string, fixed = 'fixed') => kind === 'group' + ? [child(title, fixed)] + : { path: pathToFileURL(nested).href, patches: [{ id: 'consumer', config: { title, fixed } }] } + const filename = join(root, 'cordis.yml') + await writeFile(filename, JSON.stringify([{ id: 'parent', name: `cordis:${kind}`, group: kind === 'group', config: carrierConfig('initial') }])) + const ctx = await boot('volatile-test', filename, undefined, async (ctx) => { + ctx.loader.builtins.consumer = consumer + }) + onTestFinished(() => ctx.fiber.dispose()) + expect(ctx.get('hmr')).toBeUndefined() + const parent = [...ctx.loader.entries()].find(entry => entry.options.id === 'parent')! + const entry = [...ctx.loader.entries()].find(entry => entry.options.id === 'consumer')! + const parentFiber = parent.fiber + const childFiber = entry.fiber + const original = configs[0]! + const reference = original.title + const patch = (title: string, fixed = 'fixed') => [{ id: 'parent', config: carrierConfig(title, fixed) }] + await reconcileProfilePatches(ctx, patch('first'), 'volatile-test') + await reconcileProfilePatches(ctx, patch('second'), 'volatile-test') + expect(parent.fiber).toBe(parentFiber) + expect(entry.fiber).toBe(childFiber) + expect(entry.fiber!.config).toBe(original) + expect(original.title).toBe(reference) + expect(reference.get()).toBe('second') + expect(configs).toHaveLength(1) + expect(dispose).not.toHaveBeenCalled() + expect(events).toHaveBeenCalledTimes(2) + expect(events).toHaveBeenLastCalledWith([['title']]) + await reconcileProfilePatches(ctx, patch('second'), 'volatile-test') + expect(events).toHaveBeenCalledTimes(2) + await reconcileProfilePatches(ctx, patch('mixed', 'changed'), 'volatile-test') + expect(parent.fiber).toBe(parentFiber) + expect(configs).toHaveLength(2) + expect(dispose).toHaveBeenCalledOnce() + expect(reference.get()).toBe('second') + expect(configs[1]!.title.get()).toBe('mixed') + expect(events).toHaveBeenCalledTimes(2) +}) + +it('logs an invalid candidate and keeps its references while other entries commit', async () => { + const ctx = await runtimeContext() + const events = vi.fn() + const plugin = { Config, apply(owner: Context) { owner.on('loader/volatile-update', events) } } + const invalid = await mountEntry(ctx, plugin) + const healthy = await mountEntry(ctx, plugin) + const warning = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) + onTestFinished(() => { warning.mockRestore() }) + await invalid.entry!.update({ config: { title: 'invalid', nested: { count: -1 } } }) + await healthy.entry!.update({ config: { title: 'healthy' } }) + expect(warning).toHaveBeenCalledTimes(2) + expect((invalid.config as ReturnType).title.get()).toBe('hello') + expect(invalid._config).toEqual({ title: 'invalid', nested: { count: -1 } }) + expect((healthy.config as ReturnType).title.get()).toBe('healthy') + expect(events).toHaveBeenCalledExactlyOnceWith([['title']]) +}) + +it.each([false, true])('retains raw expression edits for dependency restoration (volatile: %s)', async (volatile) => { + const ctx = await runtimeContext() + const schema = z.object({ value: volatile ? z.string().volatile() : z.string() }) + const values: unknown[] = [] + const provide = (a: string, b: string) => ctx.plugin({ apply(owner: Context) { owner.provide('volatile-expression-source', { a, b }) } }) + const provider = await provide('same', 'same') + const fiber = await mountEntry(ctx, { Config: schema, inject: ['volatile-expression-source'], apply(_owner: Context, config: ReturnType) { + values.push(typeof config.value === 'string' ? config.value : config.value.get()) + } }, { value: { __jsExpr: "ctx.get('volatile-expression-source').a" } }) + const raw = { value: { __jsExpr: "ctx.get('volatile-expression-source').b" } } + await fiber.entry!.update({ config: raw }) + await fiber.await() + expect(values).toEqual(volatile ? ['same'] : ['same', 'same']) + expect(fiber._config).toBe(raw) + await provider.dispose() + await provide('old-route', 'new-route') + await fiber.await() + expect(values).toEqual(volatile ? ['same', 'new-route'] : ['same', 'same', 'new-route']) +}) + +it('remounts when changed expressions resolve to ordinary values different from the live config', async () => { + const ctx = await runtimeContext() + const source = { a: 'initial', b: 'initial' } + ctx.provide('volatile-expression-source', source) + const configs: ReturnType[] = [] + const events = vi.fn() + const fiber = await mountEntry(ctx, { Config, apply(owner: Context, config: ReturnType) { + configs.push(config) + owner.on('loader/volatile-update', events) + } }, { fixed: { __jsExpr: "ctx.get('volatile-expression-source').a" }, title: 'old' }) + source.a = source.b = 'changed' + await update(fiber, { fixed: { __jsExpr: "ctx.get('volatile-expression-source').b" }, title: 'new' }) + expect(configs).toHaveLength(2) + expect(configs[0]!.title.get()).toBe('old') + expect(configs[1]!.fixed).toBe('changed') + expect(configs[1]!.title.get()).toBe('new') + expect(events).not.toHaveBeenCalled() +}) + +it('compares ordinary URL transforms by value and remounts when an expression result changes', async () => { + const ctx = await runtimeContext() + const source = { value: 'initial' } + ctx.provide('volatile-transform-source', source) + const schema = z.object({ + url: z.transform(z.string(), value => new URL(value), true), + fixed: z.string(), + live: z.string().volatile(), + }) + const events = vi.fn() + const mount = vi.fn(function (owner: Context) { owner.on('loader/volatile-update', events) }) + const fixed = { __jsExpr: "ctx.get('volatile-transform-source').value" } + const raw = { url: 'https://example.com/', fixed, live: 'old' } + const fiber = await mountEntry(ctx, { Config: schema, apply: mount }, raw) + const current = fiber.config as ReturnType + await update(fiber, { ...raw, live: 'new' }) + expect(mount).toHaveBeenCalledOnce() + expect(fiber.config).toBe(current) + expect(current.url.href).toBe(raw.url) + expect(current.fixed).toBe('initial') + expect(current.live.get()).toBe('new') + expect(events).toHaveBeenCalledExactlyOnceWith([['live']]) + source.value = 'changed' + await update(fiber, { ...raw, live: 'remounted' }) + expect(mount).toHaveBeenCalledTimes(2) + expect(current.fixed).toBe('initial') + expect(current.live.get()).toBe('new') + expect(events).toHaveBeenCalledOnce() + const replaced = fiber.config as ReturnType + expect(replaced.fixed).toBe('changed') + expect(replaced.live.get()).toBe('remounted') +}) + +it('remounts when an ordinary parent expression removes a live reference path', async () => { + const ctx = await runtimeContext() + const source: { block: { value: string } | undefined } = { block: { value: 'old' } } + ctx.provide('volatile-path-source', source) + const schema = z.object({ block: z.object({ value: z.string().volatile() }).extra('default', undefined), live: z.string().volatile() }) + const events = vi.fn() + const mount = vi.fn(function (owner: Context) { owner.on('loader/volatile-update', events) }) + const raw = { block: { __jsExpr: "ctx.get('volatile-path-source').block" }, live: 'old' } + const fiber = await mountEntry(ctx, { Config: schema, apply: mount }, raw) + const current = fiber.config as ReturnType + source.block = undefined + await update(fiber, { ...raw, live: 'new' }) + expect(mount).toHaveBeenCalledTimes(2) + expect(current.block.value.get()).toBe('old') + expect(events).not.toHaveBeenCalled() + expect((fiber.config as ReturnType).block).toBeUndefined() +}) + +it('keeps an ordinary plugin mounted when an absent object becomes its explicit default', async () => { + const ctx = await runtimeContext() + const Config = z.object({ nested: z.object({ fixed: z.string() }).default({ fixed: 'default' }) }) + const mount = vi.fn() + const fiber = await mountEntry(ctx, { Config, apply: mount }, {}) + const config: unknown = fiber.config + await update(fiber, { nested: { fixed: 'default' } }) + expect(fiber.config).toBe(config) + expect(mount).toHaveBeenCalledTimes(1) + await update(fiber, { nested: { fixed: 'changed' } }) + expect(mount).toHaveBeenCalledTimes(2) + expect(fiber.config).toEqual({ nested: { fixed: 'changed' } }) +}) + +it('keeps a noSave volatile value as the pending raw config across a no-op entry update', async () => { + const ctx = await runtimeContext() + const fiber = await mountEntry(ctx, { Config, apply() {} }, { title: 'saved' }) + fiber.update({ title: 'ephemeral' }, true) + await fiber.await() + expect((fiber.config as ReturnType).title.get()).toBe('ephemeral') + expect(fiber.entry!.options.config).toEqual({ title: 'saved' }) + await fiber.entry!.update({ config: { title: 'saved' } }) + expect(fiber._config).toEqual({ title: 'ephemeral' }) + expect((fiber.config as ReturnType).title.get()).toBe('ephemeral') +}) + +it('isolates a failing notification listener and dispatches with a Context receiver', async () => { + const ctx = await runtimeContext() + const receivers: unknown[] = [] + const fiber = await mountEntry(ctx, { Config, apply(owner: Context) { + owner.on('loader/volatile-update', function (this: Context) { receivers.push(this.fiber); throw new Error('listener boom') }) + } }, {}) + const other = await mountEntry(ctx, { Config, apply() {} }, {}) + const warning = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) + onTestFinished(() => { warning.mockRestore() }) + await update(fiber, { title: 'committed' }) + expect((fiber.config as ReturnType).title.get()).toBe('committed') + expect(receivers).toEqual([fiber]) + expect(warning).toHaveBeenCalledWith(expect.objectContaining({ message: 'listener boom' })) + await update(other, { title: 'unaffected' }) + expect((other.config as ReturnType).title.get()).toBe('unaffected') +}) + +it('remounts instead of committing when an ordinary field parses into a fresh class instance', async () => { + const ctx = await runtimeContext() + class Handle { constructor(public readonly name: string) {} } + const schema = z.object({ handle: z.transform(z.string(), value => new Handle(value)), live: z.string().volatile() }) + const mount = vi.fn() + const fiber = await mountEntry(ctx, { Config: schema, apply: mount }, { handle: 'h', live: 'old' }) + const before = fiber.config as ReturnType + await update(fiber, { handle: 'h', live: 'new' }) + expect(mount).toHaveBeenCalledTimes(2) + expect(before.live.get()).toBe('old') + expect((fiber.config as ReturnType).live.get()).toBe('new') +}) diff --git a/scripts/rescope-vendor.ts b/scripts/rescope-vendor.ts index 63d887a098..dd281965df 100644 --- a/scripts/rescope-vendor.ts +++ b/scripts/rescope-vendor.ts @@ -78,6 +78,8 @@ interface GenericSkip { const GENERIC_SKIPS: readonly GenericSkip[] = [ // `Symbol.for('schemastery')` and the `vendor:` metadata field are upstream identifiers. { file: 'vendor/schemastery/src/index.ts', upstream: ['schemastery'] }, + // Narrows a Standard Schema by the same upstream `vendor:` identifier. + { file: 'vendor/loader/src/config/diff.ts', upstream: ['schemastery'] }, // Asserts the vendored-manifest table, which gains an upstream-name column. { file: 'scripts/gen-third-party-notices.spec.ts', upstream: RENAMES.map(rename => rename.upstream) }, // `cordis` is also an agent-preset id — the directory name under @@ -172,6 +174,13 @@ const POSTCONDITIONS: readonly PostCondition[] = [ * quote a neighbouring line the generic pass would rewrite. */ const EXACT_EDITS: readonly ExactEdit[] = [ + { + id: 'loader-diff-schemastery-import', + file: 'vendor/loader/src/config/diff.ts', + find: "import type Schema from 'schemastery'", + replace: "import type Schema from '@deepseek-ai/schemastery'", + expect: 1, + }, { id: 'cordis-walk-merge-head', file: 'scripts/cordis-walk.ts', diff --git a/scripts/volatile-config.fixture.ts b/scripts/volatile-config.fixture.ts new file mode 100644 index 0000000000..a10df387fd --- /dev/null +++ b/scripts/volatile-config.fixture.ts @@ -0,0 +1,11 @@ +/** Shared volatile schema fixture for the schema and Loader volatile specs. */ +import z from '@deepseek-ai/schemastery' + +/** Mixed ordinary, volatile, nested and whole-object volatile fields. */ +export const Config = z.object({ + fixed: z.string().default('fixed'), + title: z.string().default('hello').volatile(), + optional: z.string().volatile(), + nested: z.object({ count: z.number().min(0).volatile().default(1) }).default({}), + group: z.object({ list: z.array(z.string()) }).default({ list: [] }).volatile(), +}) diff --git a/scripts/volatile-config.spec.ts b/scripts/volatile-config.spec.ts new file mode 100644 index 0000000000..75d2a5f1f6 --- /dev/null +++ b/scripts/volatile-config.spec.ts @@ -0,0 +1,151 @@ +/** Schemastery and Cordis config reference behavior through direct and Loader updates. */ +import { describe, expect, expectTypeOf, it } from 'vitest' +import { type Volatile } from '@deepseek-ai/cordis' +import z from '@deepseek-ai/schemastery' +import { Config } from './volatile-config.fixture.ts' +import { createVolatile, deepEqual, volatileEntries } from '@deepseek-ai/cosmokit' +import { redactSecrets } from '../packages/settings/settings/src/redact.ts' + +describe('volatile schemas', () => { + it('parses references with defaults and absent values while preserving schema metadata', () => { + const parsed = Config({}) + expect(parsed.title.get()).toBe('hello') + expect(parsed.optional.get()).toBeUndefined() + expect(parsed.nested.count.get()).toBe(1) + expectTypeOf(parsed.title).toEqualTypeOf>() + expectTypeOf(parsed.optional).toEqualTypeOf>() + expectTypeOf(parsed.nested.count).toEqualTypeOf>() + expectTypeOf(z.string().volatile().description('Live text').default('text')().get()).toEqualTypeOf() + expectTypeOf(z.string().required().volatile()('text').get()).toEqualTypeOf() + expect(Config.dict?.title?.type).toBe('string') + expect(Config.dict?.title?.meta.default).toBe('hello') + expect(Config.simplify(parsed)).toBeNull() + const reconstructed = new z(JSON.parse(JSON.stringify(Config.toJSON())) as z) + expect((reconstructed({ title: 'changed' }) as ReturnType).title.get()).toBe('changed') + expect(reconstructed.simplify(reconstructed({ title: 'changed' }))).toEqual({ title: 'changed' }) + expect(z.string().volatile().required()('present').get()).toBe('present') + expect(() => z.string().volatile().required()()).toThrow('missing required value') + expect(() => Config({ nested: { count: -1 } })).toThrow() + expect(Config({ nested: { count: -1 } }, { autofix: true }).nested.count.get()).toBe(1) + }) + + it('copies and freezes data snapshots without freezing the input', () => { + const input = { group: { list: ['a'] } } + const parsed = Config(input) + input.group.list.push('b') + expect(parsed.group.get()).toEqual({ list: ['a'] }) + expect(Object.isFrozen(parsed.group.get())).toBe(true) + expect(Object.isFrozen(parsed.group.get().list)).toBe(true) + expect(() => (parsed.group.get().list as string[]).push('c')).toThrow() + expect(Object.keys(parsed.group)).toEqual(['get']) + expect(() => z.any().volatile()(new Date())).toThrow('plain objects') + const cyclic: Record = {} + cyclic.self = cyclic + expect(() => z.any().volatile()(cyclic)).toThrow('cycles') + }) + + it.each([ + ['array', () => z.object({ items: z.array(z.string().volatile()) }), 'items'], + ['dict', () => z.object({ items: z.dict(z.string().volatile()) }), 'items'], + ['union', () => z.union([z.object({ title: z.string().volatile() }), z.string()]), 'title'], + ['tuple', () => z.object({ items: z.tuple([z.string().volatile()]) }), 'items'], + ['intersect', () => z.intersect([z.object({ title: z.string().volatile() })]), 'title'], + ['transform', () => z.transform(z.object({ title: z.string().volatile() }), value => value), 'title'], + ['nested', () => z.object({ block: z.object({ title: z.string().volatile() }).volatile() }), 'block'], + ])('rejects %s placements even when input omits the field', (_name, schema, path) => { + expect(() => schema()({})).toThrow(path) + }) + + it('rejects repeat wrapping and supports an entire array or union as a value', () => { + expect(() => z.string().volatile().volatile()).toThrow('already wrapped') + expect(z.array(z.string()).volatile()(['a']).get()).toEqual(['a']) + expect(z.union([z.string(), z.number()]).volatile()(1).get()).toBe(1) + const schema = z.string().volatile() + expect(schema('first')).not.toBe(schema('first')) + }) + + it('retains ordinary fields and secret traversal in serialized schemas', () => { + const schema = z.object({ block: z.object({ apiKey: z.string().role('secret'), title: z.string() }).volatile() }) + const restored = new z(JSON.parse(JSON.stringify(schema.toJSON())) as z) + expect(restored.dict?.block?.type).toBe('object') + expect(restored.dict?.block?.dict?.apiKey?.meta.role).toBe('secret') + expect(redactSecrets(restored as z, { block: { apiKey: 'secret', title: 'public' } }).value) + .toEqual({ block: { title: 'public' } }) + }) + + it('accepts metadata-free serialized nodes and checks their nested volatile declarations', () => { + const schema = new z<{ enabled: boolean }>(JSON.parse('{"type":"object","dict":{"enabled":{"type":"boolean"}}}') as z<{ enabled: boolean }>) + expect(schema({ enabled: true })).toEqual({ enabled: true }) + const dynamic = new z(JSON.parse( + '{"type":"object","dict":{"items":{"type":"array","inner":{"type":"string","meta":{"volatile":true}}}}}', + ) as z) + expect(() => dynamic({ items: [] })).toThrow('items') + }) + + it('resolves recursive lazy schemas only for the supplied data', () => { + interface Tree { name: string; children?: Tree[] } + function tree(): z { + return z.object({ name: z.string(), children: z.array(z.lazy(tree)).default([]) }) + } + expect(tree()({ name: 'root' })).toEqual({ name: 'root', children: [] }) + expect(tree()({ name: 'root', children: [{ name: 'leaf' }] })) + .toEqual({ name: 'root', children: [{ name: 'leaf', children: [] }] }) + const schema = z.object({ lazy: z.lazy(() => z.object({ live: z.string().volatile() })) }) + expect(() => schema({ lazy: { live: 'value' } })).toThrow('lazy') + }) +}) + +describe('volatile comparison semantics', () => { + it('ignores reference contents while retaining ordinary differences', () => { + const first = Config({ title: 'a' }) + const second = Config({ title: 'b' }) + expect(deepEqual(first, second, true)).toBe(true) + expect(deepEqual(first, Config({ fixed: 'changed' }), true)).toBe(false) + expect(deepEqual(first.title, 'a', true)).toBe(false) + expect(deepEqual('a', first.title, true)).toBe(false) + expect(deepEqual([undefined], [null], true)).toBe(false) + expect(deepEqual([undefined], [null])).toBe(true) + expect(deepEqual(new Date(0), new Date(0), true)).toBe(true) + expect(deepEqual(/a/g, /a/i, true)).toBe(false) + expect(deepEqual(new URL('https://a.example'), new URL('https://b.example'), true)).toBe(false) + expect(deepEqual(new URL('https://EXAMPLE.com:443/'), new URL('https://example.com'), true)).toBe(true) + expect(deepEqual(new URL('https://example.com'), {}, true)).toBe(false) + expect(deepEqual({}, new URL('https://example.com'), true)).toBe(false) + expect(deepEqual(new Uint8Array([1]).buffer, new Uint8Array([2]).buffer, true)).toBe(false) + const firstCycle: Record = {}; firstCycle.self = firstCycle + const secondCycle: Record = {}; secondCycle.self = secondCycle + expect(deepEqual(firstCycle, secondCycle, true)).toBe(false) + }) +}) + +it('enumerates references through shared config containers without descending into snapshots or cycles', () => { + const ref = createVolatile({ nested: 'value' }) + const shared = Object.assign(Object.create(null), { live: ref }) as Record + const config: Record = { list: [shared, shared], opaque: new URL('https://example.com'), plain: 'value' } + config.self = config + expect(volatileEntries(config)).toEqual([ + { path: ['list', '0', 'live'], ref }, + { path: ['list', '1', 'live'], ref }, + ]) + expect(volatileEntries(ref)).toEqual([{ path: [], ref }]) +}) + +it('compares sparse array slots as undefined in both directions', () => { + for (const strict of [true, false]) { + expect(deepEqual(Array(1), [undefined], strict)).toBe(true) + expect(deepEqual([undefined], Array(1), strict)).toBe(true) + expect(deepEqual(Array(1), ['new'], strict)).toBe(false) + expect(deepEqual(['new'], Array(1), strict)).toBe(false) + expect(deepEqual(Array(1), [], strict)).toBe(false) + expect(deepEqual([], Array(1), strict)).toBe(false) + } + expect(deepEqual(Array(1), [null], true)).toBe(false) + expect(deepEqual([null], Array(1), true)).toBe(false) +}) + +it('reports unsupported volatile values as validation issues with their path', () => { + const schema = z.object({ block: z.object({ when: z.date().volatile() }) }) + expect(() => schema({ block: { when: new Date(0) } })).toThrow(z.ValidationError) + expect(() => schema({ block: { when: new Date(0) } })).toThrow('$.block.when') + expect(schema({ block: {} }).block.when.get()).toBeUndefined() +}) diff --git a/vendor/README.md b/vendor/README.md index 4c9e1832ae..f6e31b6617 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -54,6 +54,8 @@ Keep this log exhaustive — every divergence from upstream must be listed. 21. **`cordis/src/logger.ts` exporter disposal**: each disposer retains its registration id, so removing an earlier exporter cannot delete a later console or telemetry exporter. Covered by startup collector cleanup in `packages/boot/app-boot/tests/app-boot.spec.ts` and disabled-feedback output in `packages/session/session-telemetry-otel/tests/loader-composition.e2e.ts`. +22. **Volatile config across `cosmokit`, `schemastery`, `cordis`, and `loader`**: Cosmokit supplies immutable references and framework-owned commits; `deepEqual` treats two references as equal, propagates strict comparison into arrays, compares every array slot with holes treated as undefined, handles cycles conservatively, compares URLs by normalized href, and compares other opaque objects by identity in strict mode. Schemastery adds `.volatile()`, optional/default inference, placement validation without eager lazy-schema expansion (a lazy inner is validated once when built), metadata-free serialized node compatibility, serialized metadata, reference-aware simplification, unsupported volatile values reported as `ValidationError` with their path, and `.default()` accepting the raw input type `Partial` because a volatile field makes the output type carry references. Loader's save path calls `simplify` with its schema receiver (`unparse.call`), an independent fix for the unbound-`this` call. Cordis exports consumer types without changing Fiber lifecycle. Loader compares raw options strictly in `Entry.update`; for a config-only change on an active fiber it calls the pure `equalExceptVolatile` function in `config/diff.ts`, which narrows the Standard Schema to Schemastery's `Schema` type (a new type-only `@deepseek-ai/schemastery` dependency of `loader`) and recursively skips fixed volatile paths using schema metadata without executing config hooks or validation. Missing or null object nodes compare using their declared defaults, including nodes without volatile descendants; schema backedges retain raw comparison. Entry passes its actual schema and preserves ordinary context and custom-update lifecycles. For a volatile-only change, `Entry._commitVolatile` re-parses the raw config through the fiber's `internal/config` hook and `resolveConfig`, compares ordinary effective values, commits references and emits the instance-local `loader/volatile-update` declared in `loader/src/index.ts`; a changed ordinary effective value falls back to the ordinary remount, and an invalid candidate is logged while the raw config stays retained for the next activation. Cosmokit provides reference enumeration and commits, and `simplify` is called with its schema receiver. The package READMEs document these additions; schema tests live in `scripts/volatile-config.spec.ts`, Loader runtime and real-file tests in `scripts/loader-volatile-update.spec.ts`, and code replacement tests in the HMR module suite. + ## Sync procedure To update a vendored package from upstream: diff --git a/vendor/cordis/README.md b/vendor/cordis/README.md index 538809ddfb..d0181dbf76 100644 --- a/vendor/cordis/README.md +++ b/vendor/cordis/README.md @@ -99,3 +99,7 @@ yarn lint The monorepo uses Yakumo to build and test all packages. Most examples in the docs use public APIs from `cordis`; loader examples additionally use `@cordisjs/plugin-loader` and `@cordisjs/plugin-include`. + +## Volatile configuration + +Schemas may return `Volatile` references, whose values are read through `.get()`. Cordis exports the consumer types; Loader commits volatile-only changes into the running references without restarting and notifies the owning fiber through `loader/volatile-update`. Direct `fiber.update()` retains its existing update waterfall and default restart. diff --git a/vendor/cordis/src/index.ts b/vendor/cordis/src/index.ts index d0814213e0..5c27008b44 100644 --- a/vendor/cordis/src/index.ts +++ b/vendor/cordis/src/index.ts @@ -12,3 +12,5 @@ export * from './registry.ts' export * from './service.ts' /** Shared internal helpers used by context, services, and plugin fibers. */ export * from './utils.ts' +/** Readonly references returned by volatile config schemas. */ +export type { Volatile, VolatileSnapshot } from '@deepseek-ai/cosmokit' diff --git a/vendor/cosmokit/README.md b/vendor/cosmokit/README.md index 5398a146c2..7cdc1d1704 100644 --- a/vendor/cosmokit/README.md +++ b/vendor/cosmokit/README.md @@ -22,3 +22,9 @@ import cosmokit from 'cosmokit' ```ts import cosmokit from 'npm:cosmokit@latest' ``` + +## Config references + +`Volatile` exposes `get()` for immutable data snapshots. `createVolatile()` copies and freezes validated data; framework-owned `updateVolatile()` transfers a candidate snapshot into an existing reference. Framework-owned `volatileEntries()` enumerates references and their paths through plain config containers, stopping at snapshots and opaque objects. The shared symbol protocol recognizes references across ESM/CJS copies. Plugin consumers import the type from Cordis and retain the reference rather than caching values between operations. + +`deepEqual()` treats two volatile references as equal regardless of their snapshots. Strict comparisons distinguish null from undefined recursively, compare URLs by normalized `href` and other opaque objects by identity, and treat distinct cyclic structures as unequal. Array comparison visits every index and treats holes as undefined. Snapshot-change detection must compare `.get()` results separately. diff --git a/vendor/cosmokit/src/index.ts b/vendor/cosmokit/src/index.ts index 9fe48de069..b6b7144168 100644 --- a/vendor/cosmokit/src/index.ts +++ b/vendor/cosmokit/src/index.ts @@ -8,3 +8,5 @@ export * from './misc.ts' export * from './string.ts' /** Time constants, parsing, and formatting helpers. */ export * from './time.ts' +/** Immutable config references shared by schema validators and runtimes. */ +export * from './volatile.ts' diff --git a/vendor/cosmokit/src/types.ts b/vendor/cosmokit/src/types.ts index 499a46273a..0aab4420c1 100644 --- a/vendor/cosmokit/src/types.ts +++ b/vendor/cosmokit/src/types.ts @@ -1,4 +1,5 @@ import { isNullable } from './misc.ts' +import { isVolatile } from './volatile.ts' type GlobalConstructorNames = keyof { [K in keyof typeof globalThis as typeof globalThis[K] extends abstract new (...args: any) => any ? K : never]: K @@ -114,29 +115,54 @@ export function clone(source: any, refs = new Map()) { return result } -/** Deeply compare arrays, dates, regexps, buffers, and plain object fields. */ +/** + * Compare values recursively, treating two volatile references as equal regardless of value. + * Strict comparison distinguishes null/undefined, treats opaque objects by identity, + * compares URLs by normalized href, treats array holes as undefined, and considers distinct cyclic structures unequal. + * @param a - first value. + * @param b - second value. + * @param strict - whether to require strict data equality outside volatile references. + * @returns whether the values compare equal. + */ export function deepEqual(a: any, b: any, strict?: boolean): boolean { - if (a === b) return true - if (!strict && isNullable(a) && isNullable(b)) return true - if (typeof a !== typeof b) return false - if (typeof a !== 'object') return false - if (!a || !b) return false + const ancestors = new Set() + function compare(a: any, b: any): boolean { + if (a === b) return true + if (isVolatile(a) || isVolatile(b)) return isVolatile(a) && isVolatile(b) + if (!strict && isNullable(a) && isNullable(b)) return true + if (typeof a !== typeof b || typeof a !== 'object' || !a || !b) return false + if (ancestors.has(a)) return false - function check(test: (x: any) => x is T, then: (a: T, b: T) => boolean) { - return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : undefined + function check(test: (x: any) => x is T, then: (a: T, b: T) => boolean) { + return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : undefined + } + + ancestors.add(a) + try { + return check(Array.isArray, (a, b) => { + if (a.length !== b.length) return false + for (let index = 0; index < a.length; index++) { + if (!compare(a[index], b[index])) return false + } + return true + }) + ?? check(is('Date'), (a, b) => a.valueOf() === b.valueOf()) + ?? check(is('URL'), (a, b) => a.href === b.href) + ?? check(is('RegExp'), (a, b) => a.source === b.source && a.flags === b.flags) + ?? check(isArrayBufferLike, (a, b) => { + if (a.byteLength !== b.byteLength) return false + const viewA = new Uint8Array(a) + const viewB = new Uint8Array(b) + for (let i = 0; i < viewA.length; i++) { + if (viewA[i] !== viewB[i]) return false + } + return true + }) + ?? ((!strict || [a, b].every(value => Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) + && Object.keys({ ...a, ...b }).every(key => compare(a[key], b[key]))) + } finally { + ancestors.delete(a) + } } - - return check(Array.isArray, (a, b) => a.length === b.length && a.every((item, index) => deepEqual(item, b[index]))) - ?? check(is('Date'), (a, b) => a.valueOf() === b.valueOf()) - ?? check(is('RegExp'), (a, b) => a.source === b.source && a.flags === b.flags) - ?? check(isArrayBufferLike, (a, b) => { - if (a.byteLength !== b.byteLength) return false - const viewA = new Uint8Array(a) - const viewB = new Uint8Array(b) - for (let i = 0; i < viewA.length; i++) { - if (viewA[i] !== viewB[i]) return false - } - return true - }) - ?? Object.keys({ ...a, ...b }).every(key => deepEqual(a[key], b[key], strict)) + return compare(a, b) } diff --git a/vendor/cosmokit/src/volatile.ts b/vendor/cosmokit/src/volatile.ts new file mode 100644 index 0000000000..a64c35f253 --- /dev/null +++ b/vendor/cosmokit/src/volatile.ts @@ -0,0 +1,86 @@ +/** Shared config references used by schema validators and plugin runtimes. */ + +const write = Symbol.for('cosmokit.volatile.write') + +/** Recursively readonly data returned by a volatile config reference. */ +export type VolatileSnapshot = T extends object ? { readonly [K in keyof T]: VolatileSnapshot } : T + +/** A stable reference; keep the reference, or capture its value for one operation only. */ +export interface Volatile { + /** @returns the current immutable snapshot, including undefined for an absent value. */ + get(): VolatileSnapshot +} + +interface WritableVolatile extends Volatile { + [write](value: unknown): void +} + +function snapshot(value: unknown, ancestors = new Set()): unknown { + if (typeof value === 'function') throw new TypeError('volatile config cannot contain functions') + if (value === null || typeof value !== 'object') return value + if (ancestors.has(value)) throw new TypeError('volatile config cannot contain cycles') + ancestors.add(value) + try { + if (Array.isArray(value)) return Object.freeze(value.map(item => snapshot(item, ancestors))) + if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) { + throw new TypeError('volatile config objects must be plain objects or arrays') + } + return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)]))) + } finally { + ancestors.delete(value) + } +} + +/** + * Create a detached reference containing an immutable copy of the supplied data. + * @param value - validated config data; class instances and functions are unsupported. + * @returns a reference whose value is updated only by its owning runtime. + */ +export function createVolatile(value: T): Volatile { + let current = snapshot(value) + return Object.freeze({ + get: () => current, + [write]: (value: unknown) => { current = value }, + }) as Volatile +} + +/** + * Identify references across ESM/CJS copies of the shared library. + * @param value - a parsed config value. + * @returns whether the value implements the shared reference protocol. + */ +export function isVolatile(value: unknown): value is Volatile { + return typeof value === 'object' && value !== null && write in value +} + +/** + * Collect config references without descending into their snapshots or opaque objects. + * @internal + * @param value - parsed config; cyclic ordinary fields are visited once per path. + * @returns references and their object-key paths, including an empty path for a root reference. + */ +export function volatileEntries(value: unknown): { path: string[]; ref: Volatile }[] { + const ancestors = new Set() + function visit(value: unknown, path: string[]): { path: string[]; ref: Volatile }[] { + if (isVolatile(value)) return [{ path, ref: value }] + if (!value || typeof value !== 'object' || ancestors.has(value)) return [] + if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return [] + ancestors.add(value) + try { + return Object.entries(value).flatMap(([key, child]) => visit(child, [...path, key])) + } finally { + ancestors.delete(value) + } + } + return visit(value, []) +} + +/** + * Commit an already validated immutable snapshot from another reference. + * @internal + * @param target - the owning plugin's stable reference. + * @param source - a newly parsed candidate reference. + */ +export function updateVolatile(target: Volatile, source: Volatile): void { + ;(target as WritableVolatile)[write](source.get()) +} diff --git a/vendor/loader/README.md b/vendor/loader/README.md index fb71b774a8..9001b2a8c2 100644 --- a/vendor/loader/README.md +++ b/vendor/loader/README.md @@ -46,3 +46,7 @@ root.loader.update(id, { config: { enabled: false } }) | `loader.locate(fiber?)` | Return the loader entry id that owns a fiber. | For file-backed trees, use `@cordisjs/plugin-include`. + +## Volatile configuration + +`Entry.update` compares raw entry options strictly; when only `config` changed on an active fiber in an unchanged context, the pure `equalExceptVolatile` function in `config/diff.ts` compares the raw configs using Schemastery metadata. It ignores volatile fields at fixed object paths without executing expressions, validators or `internal/config` hooks. Object nodes use their declared defaults for null or absent values, including objects without volatile fields; equivalent defaults skip updates. Other ordinary values, parent expressions and unknown fields retain raw comparison. Recursive schema backedges use raw comparison. Entry passes the actual plugin schema; a non-Schemastery schema compares raw. Context changes, other option changes and pending fibers use ordinary updates. A volatile-only change retains the raw Fiber config for later activation, then `_commitVolatile` parses it through the fiber's `internal/config` hook and schema, commits the new values into the running references when every ordinary effective value still matches, and emits `loader/volatile-update` to the owning fiber with the changed paths. A changed ordinary effective value uses the ordinary remount with a debug log naming the entry; because strict comparison treats class instances other than URL, Date and RegExp by identity, an ordinary field whose transform builds a fresh instance on every parse always takes that remount. An invalid candidate is logged and leaves the running references unchanged. A throwing `loader/volatile-update` listener is logged and does not fail the update; the values are already committed. Group/Include retain child dispatch, and programmatic Fiber updates preserve saving and `noSave`; `simplify` is called with its schema receiver so saved config contains plain values. diff --git a/vendor/loader/package.json b/vendor/loader/package.json index c8ad7bcd98..6ae5a43e9b 100644 --- a/vendor/loader/package.json +++ b/vendor/loader/package.json @@ -39,6 +39,7 @@ } }, "dependencies": { - "@deepseek-ai/cosmokit": "workspace:^" + "@deepseek-ai/cosmokit": "workspace:^", + "@deepseek-ai/schemastery": "workspace:^" } } diff --git a/vendor/loader/src/config/diff.ts b/vendor/loader/src/config/diff.ts new file mode 100644 index 0000000000..e97d53e5ad --- /dev/null +++ b/vendor/loader/src/config/diff.ts @@ -0,0 +1,45 @@ +/** Compare raw plugin configs using schema metadata without executing config hooks or validators. */ +import type { Plugin } from '@deepseek-ai/cordis' +import { deepEqual } from '@deepseek-ai/cosmokit' +import type Schema from '@deepseek-ai/schemastery' +import { isJsExpr } from './utils.ts' + +function isSchemastery(schema: Plugin.Runtime['Config']): schema is Schema { + return schema?.['~standard'].vendor === 'schemastery' +} + +function isRecord(value: unknown): value is Record { + if (!value || typeof value !== 'object' || isJsExpr(value)) return false + const prototype = Object.getPrototypeOf(value) + return prototype === Object.prototype || prototype === null +} + +function equal(a: unknown, b: unknown, schema: Schema | undefined, ancestors: Set): boolean { + if (schema?.meta?.volatile) return true + if (schema?.type !== 'object' || !schema.dict || ancestors.has(schema)) return deepEqual(a, b, true) + const left = a ?? schema.meta?.default + const right = b ?? schema.meta?.default + if (!isRecord(left) || !isRecord(right)) return deepEqual(left, right, true) + const { dict } = schema + ancestors.add(schema) + try { + return Object.keys({ ...left, ...right }).every(key => + equal(left[key], right[key], Object.hasOwn(dict, key) ? dict[key] : undefined, ancestors), + ) + } finally { + ancestors.delete(schema) + } +} + +/** + * Compare two raw configs, treating schema-declared volatile fields at fixed object paths as equal and absent objects as their schema default. + * Schema backedges, expressions, unknown fields and opaque values keep strict raw equality; an absent or non-Schemastery schema compares everything raw. + * @param previous - previous raw config. + * @param next - next raw config. + * @param schema - the plugin's config schema. + * @returns Whether the configs differ at most in volatile fields, without evaluating expressions, validating config or modifying inputs. + * @internal + */ +export function equalExceptVolatile(previous: unknown, next: unknown, schema: Plugin.Runtime['Config']): boolean { + return isSchemastery(schema) ? equal(previous, next, schema, new Set()) : deepEqual(previous, next, true) +} diff --git a/vendor/loader/src/config/entry.ts b/vendor/loader/src/config/entry.ts index 4aa2c473fb..8ab9f8e6a0 100644 --- a/vendor/loader/src/config/entry.ts +++ b/vendor/loader/src/config/entry.ts @@ -1,9 +1,10 @@ -import { Context, Fiber, Inject } from '@deepseek-ai/cordis' -import { deepEqual, isNullable } from '@deepseek-ai/cosmokit' +import { Context, Fiber, FiberState, Inject, resolveConfig } from '@deepseek-ai/cordis' +import { deepEqual, isNullable, updateVolatile, volatileEntries, type Volatile } from '@deepseek-ai/cosmokit' import { Loader } from '../index.ts' import { EntryGroup } from './group.ts' import { EntryTree } from './tree.ts' import { evaluate, isJsExpr } from './utils.ts' +import { equalExceptVolatile } from './diff.ts' /** Serialized plugin entry options stored in loader config files. */ export interface EntryOptions { @@ -137,17 +138,62 @@ export class Entry { // step 3: check if options are changed if (this.fiber?.uid) { - const diff = Object - .keys({ ...this.options, ...legacy }) - .filter(key => !deepEqual(this.options[key], legacy[key])) - if (!diff.length && !force) return + const changes = Object.keys({ ...this.options, ...legacy }) + .filter(key => !deepEqual(this.options[key], legacy[key], key === 'config')) + // Only an active fiber in an unchanged context takes volatile-only config changes without a remount. + const volatileOnly = changes.length === 1 && changes[0] === 'config' + && this.fiber.state === FiberState.ACTIVE && Object.getPrototypeOf(this.ctx) === this.parent.ctx + && equalExceptVolatile(legacy.config, this.options.config, this.fiber.runtime?.Config) + if (volatileOnly) this.fiber._config = this.options.config + const pending = volatileOnly && this._commitVolatile() ? [] : changes + if (!pending.length && !force) return this.context.emit('loader/partial-dispose', this, legacy, true) - this._patchContext(diff) + this._patchContext(pending) } else { await this.init() } } + /** + * Parse a volatile-only raw config change and commit its values into the running fiber's references. + * An invalid candidate is logged and leaves the running references unchanged; the raw config stays retained for the next activation. + * @returns `false` when an ordinary effective value changed, so the caller applies the ordinary update lifecycle. + */ + private _commitVolatile(): boolean { + const fiber = this.fiber! + const refs = volatileEntries(fiber.config) + if (!refs.length) return true + const raw = this.options.config + let candidate: unknown + try { + candidate = resolveConfig(fiber.runtime!, fiber.ctx.waterfall(fiber, 'internal/config', raw, () => raw)) + } catch (error) { + this.ctx.logger.warn('volatile config update failed for %C', this.options.id) + this.ctx.logger.warn(error) + return true + } + if (!deepEqual(fiber.config, candidate, true)) { + this.ctx.logger.debug('ordinary config values of %C changed with its volatile values; applying the ordinary update', this.options.id) + return false + } + const paths = refs.flatMap(({ path, ref }) => { + const source = path.reduce((value, key) => Reflect.get(value as object, key), candidate) as Volatile + if (deepEqual(ref.get(), source.get(), true)) return [] + updateVolatile(ref, source) + return [path] + }) + if (!paths.length) return true + const self: Context = Object.create(fiber.ctx) + self[Context.filter] = (owner: Context) => owner.fiber === fiber + try { + fiber.ctx.emit(self, 'loader/volatile-update', paths) + } catch (error) { + // A listener failure must not fail the entry update; every value is already committed. + this.ctx.logger.warn(error) + } + return true + } + getOuterStack = () => { let entry: Entry | undefined = this const result: string[] = [] diff --git a/vendor/loader/src/index.ts b/vendor/loader/src/index.ts index ac736ae356..51d36260a8 100644 --- a/vendor/loader/src/index.ts +++ b/vendor/loader/src/index.ts @@ -26,6 +26,18 @@ declare module '@deepseek-ai/cordis' { 'loader/config-update'(): void 'loader/entry-init'(entry: Entry): void 'loader/partial-dispose'(entry: Entry, legacy: Partial, active: boolean): void + /** + * Volatile config values were committed into the running fiber without a remount; dispatched to the owning fiber only. + * @param paths - changed config paths as key arrays; every value is committed before dispatch. + * @mode emit + */ + 'loader/volatile-update'(paths: readonly (readonly string[])[]): void + /** + * Refresh entry context before applying config. + * @param entry - entry containing the new raw config and optional current fiber. + * @param next - continue context refresh and Loader's config update. + * @mode waterfall + */ 'loader/patch-context'(entry: Entry, next: () => void): void } @@ -103,7 +115,7 @@ export class Loader extends EntryTree { ctx.on('internal/update', function (config, noSave, next) { if (!this.entry || noSave || this.parent.fiber?.entry === this.entry) return next() const unparse = this.runtime?.Config?.['simplify'] - this.entry.options.config = unparse ? unparse(config) : config + this.entry.options.config = unparse ? unparse.call(this.runtime!.Config, config) : config this.entry.parent.tree.write() return next() }, { global: true, prepend: true }) diff --git a/vendor/loader/tsconfig.json b/vendor/loader/tsconfig.json index 2db62c7b63..341a8f0949 100644 --- a/vendor/loader/tsconfig.json +++ b/vendor/loader/tsconfig.json @@ -19,6 +19,9 @@ }, { "path": "../cordis" + }, + { + "path": "../schemastery" } ] } diff --git a/vendor/schemastery/README.md b/vendor/schemastery/README.md index 24fdf3662f..54972ce4c6 100644 --- a/vendor/schemastery/README.md +++ b/vendor/schemastery/README.md @@ -387,3 +387,7 @@ const schema2 = new Schema(JSON.parse(JSON.stringify(schema1))) Schemastery also exposes the Standard Schema `~standard` property, so compatible tools can validate values without depending on Schemastery-specific APIs. + +## Volatile configuration + +`.volatile()` preserves a field's schema type and metadata while parsing its value into a stable reference read with `.get()`. Defaults remain ordinary data; absent optional fields return references containing `undefined`. `simplify()` unwraps references for persistence. See the [configuration guide](../../docs/cordis-tutorial/05-config.md#volatile-fields) for supported placements and Cordis update semantics. diff --git a/vendor/schemastery/src/index.ts b/vendor/schemastery/src/index.ts index 56a499e1cc..6edc132c49 100644 --- a/vendor/schemastery/src/index.ts +++ b/vendor/schemastery/src/index.ts @@ -1,4 +1,5 @@ import { Binary, clone, deepEqual, filterKeys, isNullable, isPlainObject, pick, valueMap, type Dict } from '@deepseek-ai/cosmokit' +import { createVolatile, isVolatile, type Volatile } from '@deepseek-ai/cosmokit' import type { StandardSchemaV1 } from '@standard-schema/spec' const kSchema = Symbol.for('schemastery') @@ -9,7 +10,7 @@ declare global { /** Convert primitive constructors, constants, and existing schemas into a schema type. */ export type From = | X extends string | number | boolean ? Schema - : X extends Schema ? X + : X extends Schema ? X : X extends typeof String ? Schema : X extends typeof Number ? Schema : X extends typeof Boolean ? Schema @@ -17,8 +18,8 @@ declare global { : X extends Constructor ? Schema : never - type TypeS1 = X extends Schema ? S : never - type Inverse = X extends Schema ? (arg: Y) => void : never + type TypeS1 = X extends Schema ? S : never + type Inverse = X extends Schema ? (arg: SchemaOutput) => void : never /** Input type accepted by a schema-like value. */ export type TypeS = TypeS1> @@ -28,7 +29,7 @@ declare global { export type Resolve = (data: any, schema: Schema, options: Options, strict?: boolean) => [any, any?] /** Input type accepted by one schema in an intersection. */ - export type IntersectS = From extends Schema ? S : never + export type IntersectS = From extends Schema ? S : never /** Output type returned by one schema in an intersection. */ export type IntersectT = Inverse> extends ((arg: infer T) => void) ? T : never @@ -85,8 +86,8 @@ declare global { dict = Schema>(inner: X, sKey?: Y): Schema, TypeS>, Dict, TypeT>> /** Accept tuple arrays where each index matches the corresponding schema. */ tuple(list: X): Schema, TupleT> - /** Accept plain objects whose declared properties match the schema dictionary. */ - object(dict: X): Schema, ObjectT> + /** Accept plain objects; infer fields from the dictionary, not the enclosing schema's output type. */ + object(dict: X): Schema>, ObjectT>> /** Accept values matching at least one schema in `list`. */ union(list: readonly X[]): Schema, TypeT> /** Accept values matching every schema in `list`, merging object outputs. */ @@ -94,7 +95,7 @@ declare global { /** Validate with `inner`, then convert the result with `callback`. */ transform(inner: X, callback: (value: TypeS, options: Schemastery.Options) => T, preserve?: boolean): Schema, T> /** Defer construction of a recursive schema until validation or serialization. */ - lazy(callback: () => X): X + lazy>(callback: () => X): X ValidationError: typeof ValidationError } @@ -112,6 +113,8 @@ declare global { export interface Meta { default?: T extends {} ? Partial : T required?: boolean + /** Parse this node as a stable config reference; its type and UI metadata remain unchanged. */ + volatile?: boolean disabled?: boolean collapse?: boolean badges?: { text: string; type: string }[] @@ -130,9 +133,9 @@ declare global { } /** Callable schema instance that validates input and returns normalized output. */ - interface Schemastery { - (data?: S | null, options?: Schemastery.Options): T - new (data?: S | null, options?: Schemastery.Options): T + interface Schemastery { + (data?: S | null, options?: Schemastery.Options): SchemaOutput + new (data?: S | null, options?: Schemastery.Options): SchemaOutput [kSchema]: true uid: number meta: Schemastery.Meta @@ -152,49 +155,54 @@ declare global { /** Format this schema as a compact TypeScript-like type string. */ toString(inline?: boolean): string /** Serialize this schema, preserving shared and recursive references. */ - toJSON(): Schema + toJSON(): Schema /** Mark nullable input as invalid unless a default supplies a fallback. */ - required(value?: boolean): Schema + required(value?: R): Schema> + /** + * Parse this config field as a stable reference containing immutable data. + * @returns a schema whose output supports get(), including when the field is absent. + */ + volatile(): Schema, NoInfer, Mode extends 'defined' | 'volatile-defined' ? 'volatile-defined' : 'volatile'> /** Hide this schema node from UI renderers. */ - hidden(value?: boolean): Schema + hidden(value?: boolean): Schema /** Return the default value instead of throwing when validation fails. */ - loose(value?: boolean): Schema + loose(value?: boolean): Schema /** Attach a renderer role and optional role-specific metadata. */ - role(text: string, extra?: any): Schema + role(text: string, extra?: any): Schema /** Attach an external documentation link. */ - link(link: string): Schema + link(link: string): Schema /** Set the fallback value used for nullable input. */ - default(value: T): Schema + default(value: T | NoInfer>): Schema> /** Attach an auxiliary comment for documentation or form UIs. */ - comment(text: string): Schema + comment(text: string): Schema /** Attach a localized or plain description for documentation or form UIs. */ - description(text: string): Schema + description(text: string): Schema /** Mark this schema node as disabled for form UIs. */ - disabled(value?: boolean): Schema + disabled(value?: boolean): Schema /** Request collapsed rendering for nested form UIs. */ - collapse(value?: boolean): Schema + collapse(value?: boolean): Schema /** Add a deprecated badge to this schema node. */ - deprecated(): Schema + deprecated(): Schema /** Add an experimental badge to this schema node. */ - experimental(): Schema + experimental(): Schema /** Require strings to match a regular expression. */ - pattern(regexp: RegExp): Schema + pattern(regexp: RegExp): Schema /** Set an inclusive maximum for numbers or collection lengths. */ - max(value: number): Schema + max(value: number): Schema /** Set an inclusive minimum for numbers or collection lengths. */ - min(value: number): Schema + min(value: number): Schema /** Set the numeric increment constraint. */ - step(value: number): Schema + step(value: number): Schema /** Add or replace an object property schema. */ - set(key: string, value: Schema): Schema + set(key: string, value: Schema): Schema /** Append a tuple, union, or intersection member schema. */ - push(value: Schema): Schema + push(value: Schema): Schema /** Remove values equal to schema defaults from normalized output. */ simplify(value?: any): any /** Return a schema clone with descriptions merged from locale messages. */ - i18n(messages: Dict): Schema + i18n(messages: Dict): Schema /** Attach arbitrary metadata consumed by form renderers and downstream tools. */ - extra(key: K, value: Schemastery.Meta[K]): Schema + extra(key: K, value: Schemastery.Meta[K]): Schema } } @@ -234,7 +242,14 @@ Object.defineProperty(ValidationError.prototype, kValidationError, { value: true, }) -type Schema = Schemastery +type SchemaMode = 'plain' | 'defined' | 'volatile' | 'volatile-defined' +type SchemaOutput = M extends 'volatile' ? Volatile + : M extends 'volatile-defined' ? Volatile : T +type SetRequired = M extends 'volatile' | 'volatile-defined' + ? R extends true ? 'volatile-defined' : 'volatile' + : R extends true ? 'defined' : 'plain' + +type Schema = Schemastery const Schema = function (options: Schema) { const schema = function (data: any, options: Schemastery.Options = {}) { @@ -405,6 +420,7 @@ Schema.prototype.pattern = function pattern(regexp) { } Schema.prototype.simplify = function simplify(this: Schema, value) { + if (isVolatile(value)) value = value.get() if (deepEqual(value, this.meta.default, this.type === 'dict')) return null if (isNullable(value)) return value if (this.type === 'object' || this.type === 'dict') { @@ -461,7 +477,36 @@ for (const key of ['default', 'link', 'comment', 'description', 'max', 'min', 's }) } +Schema.prototype.volatile = function volatile() { + if (this.meta.volatile) throw new TypeError('volatile schema is already wrapped') + return this.extra('volatile', true) +} + const resolvers: Dict = {} +const checkedVolatile = Symbol('checked-volatile-schema') + +function validateVolatileSchema(schema: Schema, path: (keyof any)[] = [], blocked = false, seen = new Map>()) { + const states = seen.get(schema) ?? new Set() + if (states.has(blocked)) return + states.add(blocked) + seen.set(schema, states) + if (schema.meta?.volatile && blocked) { + throw new ValidationError('volatile fields require a fixed object path without an enclosing volatile field', { path }) + } + const nested = blocked || !!schema.meta?.volatile + if (schema.dict) { + for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path, key], nested, seen) + } + if (schema.sKey) validateVolatileSchema(schema.sKey, [...path, ''], true, seen) + if (schema.inner && (schema.type !== 'lazy' || schema.inner[kSchema])) { + validateVolatileSchema(schema.inner, [...path, '*'], true, seen) + } + if (schema.list) { + for (let index = 0; index < schema.list.length; index++) { + validateVolatileSchema(schema.list[index]!, [...path, String(index)], true, seen) + } + } +} Schema.extend = function extend(type, resolve) { resolvers[type] = resolve @@ -469,6 +514,20 @@ Schema.extend = function extend(type, resolve) { Schema.resolve = function resolve(data, schema, options = {}, strict = false) { if (!schema) return [data] + if (!(options as Schemastery.Options & { [checkedVolatile]?: boolean })[checkedVolatile]) { + validateVolatileSchema(schema, options.path) + options = { ...options, [checkedVolatile]: true } as Schemastery.Options + } + if (schema.meta?.volatile) { + const inner = Schema(schema) + inner.meta = { ...schema.meta, volatile: false } + const [value, adapted] = Schema.resolve(data, inner, options, strict) + try { + return [createVolatile(value), adapted] + } catch (error) { + throw new ValidationError(error instanceof Error ? error.message : String(error), options) + } + } if (options.ignore?.(data, schema)) return [data] if (isNullable(data) && schema.type !== 'lazy') { @@ -582,6 +641,7 @@ Schema.extend('lazy', (data, schema, options, strict) => { if (!schema.inner![kSchema]) { schema.inner = schema.builder!() schema.inner!.meta = { ...schema.meta, ...schema.inner!.meta } + validateVolatileSchema(schema.inner!, options.path, true) } return Schema.resolve(data, schema.inner!, options, strict) }) @@ -706,7 +766,7 @@ function property(data: any, key: keyof any, schema: Schema, options: Schemaster } catch (e) { if (!options?.autofix) throw e delete data[key] - return schema.meta.default + return schema.meta.volatile ? createVolatile(schema.meta.default) : schema.meta.default } } From 4533be9531abe13662ecc869912a0672d015d2d6 Mon Sep 17 00:00:00 2001 From: imccyu Date: Mon, 21 Sep 2026 00:32:43 +0800 Subject: [PATCH 27/27] fix(chat): address presentation review findings --- .../reasoning-preview/running.expected.md | 2 + apps/web/tests/reasoning-preview.e2e.ts | 98 +++++++++++++++++++ apps/web/tsconfig.json | 1 + packages/client/ui-chat/README.i18n.yaml | 4 +- packages/client/ui-chat/README.md | 26 +++-- packages/client/ui-chat/README.zh.md | 26 +++-- .../src/client/chat/AssistantMarkdown.tsx | 2 +- .../ui-chat/src/client/chat/ReasoningRow.tsx | 2 +- packages/client/ui-chat/src/client/index.ts | 1 - .../ui-chat/src/client/presentation-policy.ts | 6 +- .../ui-chat/tests/chat-apply.client.spec.tsx | 6 ++ .../tests/reasoning-row.client.spec.tsx | 6 ++ packages/client/ui-tool/README.i18n.yaml | 4 +- packages/client/ui-tool/README.md | 2 + packages/client/ui-tool/README.zh.md | 2 + .../client/tool/components/ToolRow.module.css | 2 +- .../tool/toolviews/bash-sample.module.css | 2 +- .../tests/tool-row-styles.client.spec.ts | 8 ++ tsconfig.host.json | 1 + 19 files changed, 175 insertions(+), 26 deletions(-) create mode 100644 apps/web/tests/expected/reasoning-preview/running.expected.md create mode 100644 apps/web/tests/reasoning-preview.e2e.ts diff --git a/apps/web/tests/expected/reasoning-preview/running.expected.md b/apps/web/tests/expected/reasoning-preview/running.expected.md new file mode 100644 index 0000000000..a7837c2d66 --- /dev/null +++ b/apps/web/tests/expected/reasoning-preview/running.expected.md @@ -0,0 +1,2 @@ +- text: Running +- 'button "Think Next paragraph: inspect the loaded context and pending tools inspect the loaded context and pending tools inspect the loaded context and pending tools inspect the loaded context and pending tools inspect the loaded context and pending tools inspect the loaded context and pending tools inspect the loaded context and pending tools inspect the loaded context and pending tools"' diff --git a/apps/web/tests/reasoning-preview.e2e.ts b/apps/web/tests/reasoning-preview.e2e.ts new file mode 100644 index 0000000000..c69e4618f7 --- /dev/null +++ b/apps/web/tests/reasoning-preview.e2e.ts @@ -0,0 +1,98 @@ +/** Streaming reasoning previews through the assembled Chat and a paused model adapter. */ +import { fileURLToPath } from 'node:url' +import { chromium } from 'playwright' +import { expect, it } from 'vitest' +import { LlmAdapter, type GenerateOptions, type StreamChunk } from '@deepseek-ai/dsh-llm' +import type {} from '@deepseek-ai/dsh-agent-default-model' +import { + captureStableAria, compareOrRefreshGolden, launchWebScaffold, watchConsole, webSnapshotMode, +} from './scaffold.ts' +import { connectFreshWorkspace, newEnglishPage, writeComposerDraft } from './support.ts' + +const SUMMARY = `Next paragraph: ${'inspect the loaded context and pending tools '.repeat(8).trim()}` +const DELTAS = ['First paragraph', `\nDetails\n\n\n${SUMMARY}`, '\nMore detail'] +const UI_EXPECTED = fileURLToPath(new URL('./expected/reasoning-preview/running.expected.md', import.meta.url)) + +class PausedReasoningAdapter extends LlmAdapter { + readonly stages = DELTAS.map(text => ({ + text, + arrived: Promise.withResolvers(), + proceed: Promise.withResolvers(), + })) + + release(): void { + for (const stage of this.stages) stage.proceed.resolve(undefined) + } + + override async *stream(options: GenerateOptions): AsyncIterable { + yield { type: 'block-start', index: 0, blockType: 'reasoning' } + for (const stage of this.stages) { + yield { type: 'reasoning-delta', index: 0, text: stage.text } + stage.arrived.resolve(undefined) + await stage.proceed.promise + options.signal?.throwIfAborted() + } + yield { type: 'block-end', index: 0, block: { type: 'reasoning', text: DELTAS.join('') } } + yield { type: 'block-start', index: 1, blockType: 'text' } + yield { type: 'text-delta', index: 1, text: 'Done' } + yield { type: 'block-end', index: 1, block: { type: 'text', text: 'Done' } } + yield { type: 'finish', reason: { kind: 'stop' } } + } +} + +it('shows completed paragraph first lines across blank lines with a right-edge fade', async () => { + const scaffold = await launchWebScaffold() + const adapter = new PausedReasoningAdapter() + try { + scaffold.ctx.effect(() => scaffold.ctx.llm.registerAdapter(['reasoning-preview-test'], adapter)) + await scaffold.ctx.agentDefaultModel.saveSelection({ provider: 'reasoning-preview-test', model: 'paused' }) + const browser = await chromium.launch() + try { + const page = await newEnglishPage(browser) + const console = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await connectFreshWorkspace(page, scaffold.workspaceCwd) + await page.setViewportSize({ width: 480, height: 1000 }) + const input = page.locator('[data-composer-input]').first() + const settled = scaffold.whenTurnSettled() + await writeComposerDraft(page, input, 'Show a streamed reasoning preview.') + await input.press('Enter') + + const [first, second, third] = adapter.stages + if (first === undefined || second === undefined || third === undefined) throw new Error('preview stages are incomplete') + await first.arrived.promise + const reasoning = page.locator('[data-variant="think"][data-state="running"]') + await reasoning.waitFor() + expect(await reasoning.getAttribute('data-preview')).toBeNull() + + first.proceed.resolve(undefined) + await second.arrived.promise + const preview = reasoning.locator('[data-streaming]') + await expect.poll(() => preview.textContent()).toBe('First paragraph') + expect(await preview.isVisible()).toBe(true) + await preview.evaluate((element) => { element.setAttribute('data-retained-preview', 'true') }) + + second.proceed.resolve(undefined) + await third.arrived.promise + await expect.poll(() => preview.textContent()).toBe(SUMMARY) + expect(await preview.getAttribute('data-retained-preview')).toBe('true') + expect(await preview.evaluate(element => getComputedStyle(element).maskImage)).toContain('linear-gradient') + expect(await preview.evaluate(element => element.scrollWidth > element.clientWidth)).toBe(true) + expect(await reasoning.getByRole('button').getAttribute('aria-expanded')).toBe('false') + await compareOrRefreshGolden(UI_EXPECTED, + await captureStableAria(page, '[data-variant="think"]', scaffold.workspaceCwd), webSnapshotMode()) + + third.proceed.resolve(undefined) + await settled + await page.getByText('Done', { exact: true }).waitFor() + expect(console.pageErrors).toEqual([]) + expect(console.warnings).toEqual([]) + } finally { + adapter.release() + await browser.close() + } + } finally { + adapter.release() + await scaffold.close() + } +}) diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 4e8faba00b..719f04f24d 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -44,6 +44,7 @@ "tests/chat-scroll-fixture.ts", "tests/trajectory-virtualization.e2e.ts", "tests/lifecycle-chrome.e2e.ts", + "tests/reasoning-preview.e2e.ts", "tests/details-session-lifecycle.e2e.ts", "tests/sessionless-header.e2e.ts", "tests/document-preview.e2e.ts", diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index 489c1e8723..1eefd3ba94 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-chat/README.md -README.md: 3a0e74332a0ee2c5453a024f1ffe9dfbb9ae0163 -README.zh.md: 89a385a61f08efa86c98d59fd4271f99c3b25210 +README.md: 2beb4dfadddec0c834c3ef6f4b56826be120baa6 +README.zh.md: 5d643f4e90b77d2b79ab1bb1c003b399c202e004 diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md index 3a0e74332a..2beb4dfadd 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -8,14 +8,14 @@ English | [中文](README.zh.md) ## Summary -Use this package to render a browser chat from recorded Session conversations, including historical images, localized actions, and restored scroll position. Compact display folds completed-turn process rows while keeping the final answer and independently useful context visible; packed historical Assistant runs remain collapsed. Local transcript and steering submissions appear immediately, remain in their original surface, and disappear atomically when authoritative Session records arrive, while queued submissions stay outside Chat. The package does not assemble or modify model requests. +Use this package to render a browser chat from recorded Session conversations, including historical images, localized actions, and restored scroll position. Work-details modes control reasoning previews and fold eligible completed-turn process rows without hiding final answers. Local transcript and steering submissions appear immediately, remain in their original surface, and disappear atomically when authoritative Session records arrive, while queued submissions stay outside Chat. The package does not assemble or modify model requests. File-mention providers receive the viewed Session ID with the closing-turn owner, so links into inherited history can address the fork itself. ## Table of Contents - [Reference previews](#reference-previews) -- [System prompt row](#system-prompt-row) +- [Hidden Chat rows](#system-prompt-row) - [Command and failure rows](#command-and-failure-rows) - [Turn token usage](#turn-token-usage) - [Completed-turn footer](#completed-turn-footer) @@ -35,9 +35,9 @@ Chat supplies file and HTTP(S) navigation through one `MarkdownDelegateProvider` Settings → General → Open chat links in selects the destination for ordinary clicks on Chat HTTP(S) links: Built-in browser (default) opens a new right-Sidebar Browser tab, while New browser tab opens an external tab. The setting is shown only while the built-in browser is available. If the Sidebar Browser is not registered, both choices use the external browser; modified clicks retain native behavior. The `ui-chat.linkOpening` preference persists on loopback browsers and stays process-local when settings cannot persist writes. Sent file references and skills confirmed by the message’s logged invocation also open in the right Sidebar. File paths use the viewed Session; skill names resolve through its current input-trigger source. Both use the prose file-link dotted underline on hover or focus. Sessions, directories, and command labels remain non-navigating references. -## System prompt row +## Hidden Chat rows -Each nonempty appended `system/message` owns a collapsed prompt row, including a complete prompt at the start of a headerless window; the same-step header does not duplicate it. Chat also shows a collapsed `System prompt` row for a non-empty initial request, explicit message-series start, or `system/message` surface node replacement whose text differs, reading the last nonempty surviving system node in surface order at the `request/header`; a non-initial request whose preceding header is outside the loaded history window also shows one. A resume repeats the row even when its system text is unchanged, including after pagination supplies the preceding header and system node; same-series config-only or tool-only changes, tool steps, and retries create no repetition, and a `system/message` event is never rendered as a transcript message. The row appears before that request's user messages, matching the provider envelope, and expands to the exact model-visible text with its original line breaks. A request whose system node is empty or outside the loaded window creates no row until the page holding the node arrives. +Chat omits system-prompt and `permission` command rows in every work-details mode. The filter changes neither recorded Session events nor Trajectory inspection. Ordinary Context injection and other command rows remain in Chat; Context injection can fold with the owning Turn's process content. ## Command and failure rows @@ -65,11 +65,23 @@ The completed-turn action footer starts 20px below the preceding prose or extens ## Turn Process Folding -Each reasoning row starts collapsed, including during streaming and in reasoning-only replies. Clicking the row opens or closes its complete Markdown; incoming answer text, Tool calls, and stream completion preserve that choice. Expanded reasoning uses compact secondary typography: headings add bold weight without changing text size, line height, or color. The collapsed summary stays on one line, follows the latest reasoning line while streaming, and shows the first line after settlement. +Each reasoning row starts collapsed, including during streaming and in reasoning-only replies. Clicking the row opens or closes its complete Markdown; incoming answer text, Tool calls, and stream completion preserve that choice. Expanded reasoning uses compact secondary typography: headings add bold weight without changing text size, line height, or color. While streaming, all modes preview the latest paragraph whose first line ends with a newline. Further text in that paragraph does not change the preview; an unfinished single line has no preview. One or more blank lines separate paragraphs. The one-line preview fades at the right edge. After settlement, Compact hides the preview, while Detailed and Expanded show the full text's first line. Reasoning rows retain the disclosure's callback, icon, and unchanged content references. Each reasoning row selects its preview visibility from the display policy; mode changes toggle CSS display without unmounting the collapsed summary or updating its parent Assistant renderer. Full Markdown elements are created only while expanded. -Settings → General exposes a persisted, localized `Normal` / `Compact` conversation-display preference in the `ui-chat` namespace; `Compact` is the default. Normal leaves process rows visible and renders no Turn-process control. In Compact mode, the System prompt remains independently visible before the opening User throughout the Turn. Context injection, reasoning, Assistant material, Tool rows, and Retry rows remain expanded while a Turn is open. At `turn/end`, its latest Step becomes the final-answer boundary only when it contains non-blank text, an image, or an unknown visible block—and no Tool-call block; preceding Context injection, reasoning, earlier Assistant material, Tool rows, and Retry rows then collapse by default. The control reports Turn-wide durable counts for non-subagent Tool calls, reply-bearing Assistant messages before the final answer, and subagent delegation calls; zero-valued segments are omitted, the Tool and subagent figures are mutually exclusive, and neither System prompt nor Context injection contributes a count. When all three counts are zero, the process still folds and the control reads `Thought for a while`. A full-width divider below the summary separates it from the answer or expanded process rows. User and steering messages, System prompt, error, max-token, and turn-tail rows stay outside, and a closed Turn with no final answer keeps all process evidence visible. A newly available process control is inserted without changing the relative order of existing rows: opening human input precedes the control and process rows from their first projection, while System prompt remains above that input. While older history remains available through Load earlier, process controls stay absent and no members are hidden; once history is complete, every eligible closed Turn uses the collapsed default immediately. Stable Chat Node Seats keep every renderer mounted, hidden members add no flow spacing, and a closed control sits 8px above its answer only when no independent input intervenes. Completion collapse does not depend on tail-follow position, so a reader above the tail may see the transcript reflow. An automatic collapse that would hide keyboard focus keeps the group open and leaves focus in place; a manual close focuses the process control before hiding its members. The session-scoped store records only manually expanded Turn-and-answer-Step generations; a different answer generation starts collapsed. +Settings → General → Work details stores `ui-chat.transcriptView` as `compact` (default), `detailed`, or `expanded`. A saved legacy `normal` value reads as `detailed` without being written back; it is not offered as an option. + +| Behavior | Compact | Detailed | Expanded | +|---|---|---|---| +| Settled reasoning preview | Think title only | First line | First line | +| Individual reasoning and tool bodies | Manual expansion | Manual expansion | Manual expansion | +| Eligible completed-Turn process | Folded by default | Folded by default | Folded by default | + +While a Turn is open, its process rows remain in the transcript; individual reasoning and tool disclosures retain their own expansion state. At `turn/end`, its latest Step becomes the final-answer boundary only when it contains non-blank text, an image, or an unknown visible block—and no Tool-call block. If that Turn's `turn/start` is loaded, preceding Context injection, reasoning, earlier Assistant material, Tool rows, and Retry rows fold by default. Folding eligibility is per Turn: a complete Turn can fold while Load earlier remains available, and a Turn whose start is missing keeps its process content visible until that start arrives. A closed Turn with no final answer also keeps all process evidence visible. + +The control reports Turn-wide durable counts for non-subagent Tool calls, reply-bearing Assistant messages before the final answer, and subagent delegation calls. Zero-valued segments are omitted; the Tool and subagent figures are mutually exclusive, and Context injection contributes no count. When all three counts are zero, the process still folds and the control reads `Thought for a while`. A full-width divider below the summary separates it from the answer or expanded process rows. User and steering messages, error, max-token, and turn-tail rows stay outside. A newly available process control preserves existing row order, with opening human input before the control and process rows. + +Stable Chat Node Seats keep every renderer mounted, hidden members add no flow spacing, and a closed control sits 8px above its answer only when no independent input intervenes. Completion collapse does not depend on tail-follow position, so a reader above the tail may see the transcript reflow. An automatic collapse that would hide keyboard focus keeps the process open and leaves focus in place; a manual close focuses the process control before hiding its members. The session-scoped store records only manually expanded Turn-and-answer-Step generations; a different answer generation starts collapsed. Switching work-details modes preserves manual expansion. ----- @@ -104,6 +116,8 @@ None; Chat presentation does not assemble or mutate provider requests. +- **Secondary process grouping is not implemented** — Detailed and Expanded currently display the same Chat content. Expanded retains whole-Turn folding and does not automatically open individual reasoning or tool bodies. + - **Developer messages are not displayed** — presentation is intentionally deferred; encountering `developer/message` throws instead of rendering a fallback row. - **The transcript reflects the loaded Session window** — older transcript nodes become available only after Session Controller loads the preceding event page. Turn navigation is wider than the window: the rail merges the loaded Turns with the host `turnOutline` projection, so every started Turn gets a fixed-pitch mark (10px apart; a ladder taller than the frame scrolls inside it with gradient fades), and activating an unloaded mark pages history through the Turn's `turn/start` seq before landing on its row. Without the projection (assemblies not mounting `dsh-session-turn-outline`) the rail falls back to loaded Turns only. diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index 89a385a61f..5d643f4e90 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -8,14 +8,14 @@ kind: "package-reference" ## 概述 -使用本包可在浏览器中渲染已记录的 Session 对话,包括历史图片、本地化操作和滚动位置恢复。紧凑显示会收起已完成轮次的过程行,同时保持最终答案和独立有用的上下文可见;已打包的历史 Assistant 连续消息保持收起。本地 transcript(文本记录)与 steering(中途引导)提交会立即显示并保留在原区域,在权威会话记录到达时原子地消失,而排队中的提交始终不进入 Chat。本包不组装或修改模型请求。 +使用本包可在浏览器中渲染已记录的 Session 对话,包括历史图片、本地化操作和滚动位置恢复。工作过程展示模式控制思考预览,并收起符合条件的已完成轮次过程行,不隐藏最终答案。本地 transcript(文本记录)与 steering(中途引导)提交会立即显示并保留在原区域,在权威会话记录到达时原子地消失,而排队中的提交始终不进入 Chat。本包不组装或修改模型请求。 文件提及提供方同时接收当前查看的会话 ID 与收尾轮次的属主信息,因此继承历史中的链接可以指向 fork 自身。 ## 目录 - [引用预览](#reference-previews) -- [系统提示词行](#system-prompt-row) +- [Chat 隐藏的行](#system-prompt-row) - [指令与失败行](#command-and-failure-rows) - [轮次 token 用量](#turn-token-usage) - [已完成轮次的页脚](#completed-turn-footer) @@ -35,9 +35,9 @@ Chat 在节点列表外通过一个 `MarkdownDelegateProvider` 提供文件及 H 设置 → 通用设置 → 聊天链接打开方式控制普通点击 Chat HTTP(S) 链接时的目标:「内置浏览器」(默认)打开新的右侧 Sidebar Browser tab,「浏览器新标签页」打开外部标签页。该设置项仅在内置浏览器可用时显示。若 Sidebar Browser 未注册,两种选择均使用外部浏览器;带修饰键的点击保留原生行为。`ui-chat.linkOpening` 偏好在回环地址浏览器中持久化,设置无法持久化写入时仅在当前进程内生效。已发送的文件引用及消息日志确认调用的 skill 也可在右侧栏打开预览。文件路径使用当前查看的 Session;skill 名称由该 Session 当前的输入触发源解析。两者悬停或聚焦时均使用正文文件链接的虚线下划线。会话、目录和命令标签仍只作为引用展示。 -## 系统提示词行 +## Chat 隐藏的行 -每个非空追加的 `system/message` 都拥有一行折叠提示词,包括无 header 窗口起点的完整提示词;同一步骤的 header 不会重复它。Chat 也会为非空的初始请求、显式消息序列起点、文本发生变化的 `system/message` surface 节点替换(文本读取自 `request/header` 处 surface 顺序中最后一个非空存活系统节点),或前序 header 尚未进入已加载历史窗口的非初始请求显示一行默认折叠的 `系统提示词`。即使系统文本未变,恢复也会重复该行,包括分页补齐前序 header 和系统节点后;同一序列内仅配置或仅工具变化、工具步骤与重试不会重复,且 `system/message` 事件绝不会渲染为对话消息。该行位于请求的用户消息之前,与提供方 envelope 顺序一致;展开后显示模型所见的确切文本,并保留其原始换行。系统节点为空或位于已加载窗口之外的请求不创建该行,直到包含该节点的分页到达。 +Chat 在所有工作过程展示模式下都不显示系统提示词行和 `permission` 命令行。该过滤不改变已记录的 Session 事件或 Trajectory 查看能力。普通上下文注入和其他命令行仍保留在 Chat 中;上下文注入可随所属轮次的过程内容一起收起。 ## 指令与失败行 @@ -65,11 +65,23 @@ Chat 在节点列表外通过一个 `MarkdownDelegateProvider` 提供文件及 H ## 轮次过程折叠 -每个思考行初始都折叠,包括流式输出期间和仅含思考的回复。点击该行可展开或收起完整 Markdown;后续回答文本、工具调用和流结束都保留用户的选择。展开的思考采用紧凑的次级排版:标题只加粗,不改变字号、行高或颜色。折叠摘要保持单行,在流式输出期间跟随最新思考行,结算后显示第一行。 +每个思考行初始都折叠,包括流式输出期间和仅含思考的回复。点击该行可展开或收起完整 Markdown;后续回答文本、工具调用和流结束都保留用户的选择。展开的思考采用紧凑的次级排版:标题只加粗,不改变字号、行高或颜色。流式输出期间,三档都预览最近一个首行以换行符结束的段落;该段落后续文本不会改变预览,未写完的单行不显示预览。一个或多个空行分隔段落。预览保持单行,右侧渐隐。结算后,「简洁」隐藏预览,「详细」和「完全展开」显示全文首行。 思考行保留折叠控件的回调、图标和未变化内容的引用。每个思考行从展示策略中选择预览可见性;模式切换只改变 CSS 显示状态,不卸载折叠摘要,也不更新其父级 Assistant 渲染器。完整 Markdown 元素仅在展开时创建。 -「设置 → 通用设置」提供持久化到 `ui-chat` 命名空间的「标准」/「紧凑」对话显示偏好,默认使用「紧凑」。标准模式保持所有过程行可见且不渲染轮次过程控件。紧凑模式下,系统提示词在整个轮次中始终独立显示于开场 User 上方。轮次打开期间,上下文注入、推理、Assistant 内容、工具行与重试行始终展开。到 `turn/end` 时,最后一个步骤只有在包含非空文本、图片或未知可见块且不含工具调用块时才成为最终答案边界;边界之前的上下文注入、推理、较早 Assistant 内容、工具行与重试行随后默认收起。控件展示覆盖整个轮次的非 subagent 工具调用数、最终答案之前带回复内容的 Assistant 消息数和 subagent 委派数;值为 0 的分段省略,工具调用与 subagent 两项互斥,系统提示词与上下文注入都不增加计数。三项全为 0 时过程仍会收起,控件标题显示「已思考」(英文为 `Thought for a while`)。摘要下方的通栏分隔线将其与正文或展开后的过程行隔开。用户与 steering 消息、系统提示词、错误、最大 token 与 turn-tail 行留在过程组外;关闭时没有最终答案的轮次保留全部过程证据。新的过程控件插入时不会改变既有行的相对顺序:开场人工输入从首次投影起便位于控件和过程行之前,系统提示词则始终位于该输入上方。只要仍可通过「加载更早」获取历史,过程控件就不出现,也不会隐藏任何成员;历史加载完整后,每个合格的已关闭轮次立即使用默认收起状态。稳定 Chat Node Seat 会让每个 renderer 保持挂载,隐藏成员不产生消息流间距;只有中间没有独立输入时,收起控件才与正文相隔 8px。完成后的收起不依赖是否跟随尾部,因此正在上方阅读的用户可能看到 transcript 重排。若自动收起会隐藏当前键盘焦点,则过程组保持展开且焦点留在原处;手动收起会先把焦点移到过程控件,再隐藏成员。会话作用域存储只记录用户手动展开的「轮次 + 正文步骤」generation;不同正文 generation 默认收起。 +「设置 → 通用设置 → 工作过程展示」将 `ui-chat.transcriptView` 保存为 `compact`(默认)、`detailed` 或 `expanded`。已保存的旧值 `normal` 读取为 `detailed`,不自动回写,也不再作为选项提供。 + +| 行为 | 简洁 | 详细 | 完全展开 | +|---|---|---|---| +| 已完成思考的预览 | 只显示「思考」标题 | 首行 | 首行 | +| 单个思考与工具正文 | 手动展开 | 手动展开 | 手动展开 | +| 符合条件的已完成轮次过程 | 默认收起 | 默认收起 | 默认收起 | + +轮次打开期间,过程行保留在 transcript 中,单个思考与工具控件各自保留开合状态。到 `turn/end` 时,最后一个步骤只有在包含非空文本、图片或未知可见块且不含工具调用块时才成为最终答案边界。若该轮次的 `turn/start` 已加载,边界之前的上下文注入、思考、较早 Assistant 内容、工具行与重试行默认收起。折叠资格逐轮判断:即使仍可「加载更早」,完整轮次也能收起;缺少起点的轮次则保持过程内容可见,直到该起点加载。关闭时没有最终答案的轮次也保留全部过程证据。 + +控件展示覆盖整个轮次的非 subagent 工具调用数、最终答案之前带回复内容的 Assistant 消息数和 subagent 委派数。值为 0 的分段省略;工具调用与 subagent 两项互斥,上下文注入不增加计数。三项全为 0 时过程仍会收起,控件标题显示「已思考」(英文为 `Thought for a while`)。摘要下方的通栏分隔线将其与正文或展开后的过程行隔开。用户与 steering 消息、错误、最大 token 与 turn-tail 行留在过程之外。新的过程控件保留既有行的相对顺序,开场人工输入位于控件和过程行之前。 + +稳定 Chat Node Seat 会让每个 renderer 保持挂载,隐藏成员不产生消息流间距;只有中间没有独立输入时,收起控件才与正文相隔 8px。完成后的收起不依赖是否跟随尾部,因此正在上方阅读的用户可能看到 transcript 重排。若自动收起会隐藏当前键盘焦点,则过程保持展开且焦点留在原处;手动收起会先把焦点移到过程控件,再隐藏成员。会话作用域存储只记录用户手动展开的「轮次 + 正文步骤」generation;不同正文 generation 默认收起。切换工作过程展示模式会保留手动展开状态。 ----- @@ -104,6 +116,8 @@ Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点,并且 +- **二级过程分组尚未实现**——「详细」与「完全展开」目前展示相同的 Chat 内容。「完全展开」仍保留整轮折叠,不会自动打开单个思考或工具正文。 + - **不展示 developer 消息** — 展示能力有意留待后续实现;遇到 `developer/message` 时抛出错误,不渲染回退行。 - **transcript 只反映已加载的 Session 窗口**——只有会话控制器加载前一页事件后,更早的 transcript node 才会出现。轮次导航比窗口更宽:轨道把已加载的轮次与宿主 `turnOutline` 投影合并,每个已开始的轮次都有固定间距刻度(相隔 10px;阶梯高于外框时在框内滚动并以渐变淡出标示可滚方向),激活未加载刻度会先把历史分页拉到该轮次的 `turn/start` seq 再落到它的行上。没有该投影时(未挂载 `dsh-session-turn-outline` 的装配),轨道回退到仅显示已加载轮次。 diff --git a/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx b/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx index 967a7a09b1..da45e543a9 100644 --- a/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx +++ b/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx @@ -29,7 +29,7 @@ export interface AssistantMarkdownProps { interrupted?: boolean | undefined /** Render consecutive image blocks through the attachment slot. */ renderMessageImages: ChatNodeOwnerProps['renderMessageImages'] - /** Hide reasoning that belongs to the Turn-level process disclosure or a collapsed step group. */ + /** Hide reasoning that belongs to the Turn-level process disclosure. */ reasoningHidden?: boolean | undefined /** Live display policy for reasoning summaries. */ usePresentation: UsePresentation diff --git a/packages/client/ui-chat/src/client/chat/ReasoningRow.tsx b/packages/client/ui-chat/src/client/chat/ReasoningRow.tsx index 53d1ab2a55..6e24934099 100644 --- a/packages/client/ui-chat/src/client/chat/ReasoningRow.tsx +++ b/packages/client/ui-chat/src/client/chat/ReasoningRow.tsx @@ -16,7 +16,7 @@ function firstLine(text: string): string { function latestCompletedParagraphFirstLine(text: string): string { let summary = '' let paragraphStart = 0 - const separator = /\r?\n[\t ]*\r?\n/g + const separator = /\r?\n(?:[\t ]*\r?\n)+/g while (true) { const nextParagraph = separator.exec(text) const paragraphEnd = nextParagraph === null ? text.length diff --git a/packages/client/ui-chat/src/client/index.ts b/packages/client/ui-chat/src/client/index.ts index 6bef23a2c5..20e33d8885 100644 --- a/packages/client/ui-chat/src/client/index.ts +++ b/packages/client/ui-chat/src/client/index.ts @@ -31,7 +31,6 @@ export type { ChatStoreState, ToolCallId, TurnProcessViewEntry } from './contrac export type { TranscriptViewRowInjected, TranscriptViewRowProps } from './settings/TranscriptViewRow.tsx' export type { TranscriptViewMode } from '../chat-settings.ts' export type { ChatPresentationPolicy } from './presentation-policy.ts' -export { derivePresentationPolicy, presentationPolicyFor } from './presentation-policy.ts' export type { AssistantActionOwnerProps, ChatFileMentions, ChatNodeOwnerProps, ChatNodeTurnDataInjected, ChatNodeViewProps, ChatScrollPosition, ChatStore, ChatViewInjected, ChatViewSlotProps, diff --git a/packages/client/ui-chat/src/client/presentation-policy.ts b/packages/client/ui-chat/src/client/presentation-policy.ts index 9221afa711..c1af53db51 100644 --- a/packages/client/ui-chat/src/client/presentation-policy.ts +++ b/packages/client/ui-chat/src/client/presentation-policy.ts @@ -13,11 +13,7 @@ export interface ChatPresentationPolicy { readonly mode: TranscriptViewMode /** Whether a normally completed Turn folds its process rows behind the whole-Turn control. */ readonly foldCompletedTurns: boolean - /** - * How consecutive process rows between Assistant replies present: `collapsed` - * groups them behind a step-group row that starts closed; `none` renders - * every row directly under the whole-Turn control with no group rows. - */ + /** Reserved secondary-grouping preference; no renderer consumes this field yet. */ readonly stepGrouping: 'collapsed' | 'none' /** Whether a settled reasoning row previews its first line beside the Think title. */ readonly settledReasoningPreview: boolean diff --git a/packages/client/ui-chat/tests/chat-apply.client.spec.tsx b/packages/client/ui-chat/tests/chat-apply.client.spec.tsx index b1d06a825d..54d79ecb0d 100644 --- a/packages/client/ui-chat/tests/chat-apply.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-apply.client.spec.tsx @@ -88,6 +88,12 @@ function storeOf(runtime: SlotTestRuntime, key: 'conversation.session' | 'conver } describe('Chat apply wiring', () => { + it('keeps presentation-policy helpers out of the public browser entry', async () => { + const entry = await import('../src/client/index.ts') + expect(entry).not.toHaveProperty('derivePresentationPolicy') + expect(entry).not.toHaveProperty('presentationPolicyFor') + }) + it('contributes Chat View, node renderers, and stats', async () => { const b = await bench() const views = b.runtime.slots.entries('conversation.view') diff --git a/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx b/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx index c729a91634..e0ce4a1b1e 100644 --- a/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx +++ b/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx @@ -26,6 +26,12 @@ describe('ReasoningRow', () => { ['First\nSecond\nThird\n', 'First'], ['First\n\nNext unfinished', 'First'], ['First\n\nNext complete\nDetails', 'Next complete'], + ['First\n\n\nNext complete\n', 'Next complete'], + ['First\n \n\t\nNext complete\nDetails', 'Next complete'], + ['First\r\n\r\n\r\nNext complete\r\n', 'Next complete'], + ['First\r\n \r\n\t\r\nNext complete\r\nDetails', 'Next complete'], + ['First\n\n\nNext unfinished', 'First'], + ['\n\n\nFirst complete\n', 'First complete'], ['First\r\n \t\r\nNext complete\r\n', 'Next complete'], ['First\n\n\n', 'First'], ])('previews the completed paragraph first line for %j', (text, summary) => { diff --git a/packages/client/ui-tool/README.i18n.yaml b/packages/client/ui-tool/README.i18n.yaml index ce636be50c..72abda5bc3 100644 --- a/packages/client/ui-tool/README.i18n.yaml +++ b/packages/client/ui-tool/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-tool/README.md -README.md: 6a63c14d163742b1818320925248405831bd87b6 -README.zh.md: e53a97404ae17f0e93242c11dcc0b1f066542c12 +README.md: 3e216d9670f4fa58b0590f8cede54927d947d56d +README.zh.md: 6445ee9d62555de36901300809955b7cb227f66f diff --git a/packages/client/ui-tool/README.md b/packages/client/ui-tool/README.md index 6a63c14d16..3e216d9670 100644 --- a/packages/client/ui-tool/README.md +++ b/packages/client/ui-tool/README.md @@ -27,6 +27,8 @@ English | [中文](README.zh.md) Tool calls appear in the conversation as cards: a root call tree with its nested subcalls, each atomic call rendered by its owning view. Every lifecycle state retains the tool's ordinary business glyph; failure and interruption remain explicit through the frozen call/result state, accessible status text, and failure summary. Users can open files or inspect calls through the Host callbacks. +Shared Tool rows and Bash rows retain error and warning colors for failed and stopped summaries, including on hover. Hover darkens only summaries without those states. + ### Registering a business tool view An owning business package registers its wire Tool name into `tool.call.toolview`: diff --git a/packages/client/ui-tool/README.zh.md b/packages/client/ui-tool/README.zh.md index e53a97404a..6445ee9d62 100644 --- a/packages/client/ui-tool/README.zh.md +++ b/packages/client/ui-tool/README.zh.md @@ -27,6 +27,8 @@ kind: "package-reference" 工具调用在对话中显示为卡片:一个根调用树带其嵌套子调用,每个原子调用由所属视图渲染。所有生命周期状态都保留工具的普通业务图标;失败与中断仍通过冻结调用/结果状态、无障碍状态文本和失败摘要明确表达。用户可通过宿主回调打开文件或检查调用。 +共享工具行和 Bash 行的失败、停止摘要在悬停时仍保留错误色和警告色;只有不处于这两种状态的摘要会在悬停时加深。 + ### 注册业务工具视图 拥有该视图的业务包将其 wire 工具名称注册进 `tool.call.toolview`: diff --git a/packages/client/ui-tool/src/client/tool/components/ToolRow.module.css b/packages/client/ui-tool/src/client/tool/components/ToolRow.module.css index 3bf04ae4ac..1478b06961 100644 --- a/packages/client/ui-tool/src/client/tool/components/ToolRow.module.css +++ b/packages/client/ui-tool/src/client/tool/components/ToolRow.module.css @@ -76,7 +76,7 @@ } .row:hover .title, -.row:hover .summary:not(.errorSummary), +.row:hover .summary:not(.errorSummary):not(.stoppedSummary), .row:hover .summarySuffix { color: var(--dsw-alias-label-primary); } diff --git a/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.module.css b/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.module.css index be9b547ce6..9ef5b4b829 100644 --- a/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.module.css +++ b/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.module.css @@ -172,7 +172,7 @@ } .root:hover .title, -.root:hover .summary:not(.errorSummary) { +.root:hover .summary:not(.errorSummary):not(.stoppedSummary) { color: var(--dsw-alias-label-primary); } diff --git a/packages/client/ui-tool/tests/tool-row-styles.client.spec.ts b/packages/client/ui-tool/tests/tool-row-styles.client.spec.ts index 28913a2939..db05c7f769 100644 --- a/packages/client/ui-tool/tests/tool-row-styles.client.spec.ts +++ b/packages/client/ui-tool/tests/tool-row-styles.client.spec.ts @@ -22,6 +22,14 @@ function declarations(selector: string): string[] { } describe('ToolRow.module.css summary line', () => { + it.each([ + ['ToolRow', '../src/client/tool/components/ToolRow.module.css'], + ['BashRow', '../src/client/tool/toolviews/bash-sample.module.css'], + ] as const)('%s keeps stopped and error summaries outside hover darkening', (_name, path) => { + const sheet = readFileSync(fileURLToPath(new URL(path, import.meta.url)), 'utf8') + expect(sheet).toContain('.summary:not(.errorSummary):not(.stoppedSummary)') + }) + it('keeps the summary suffix on one line and unshrunk', () => { // `flex: none` stops the box shrinking, not the text wrapping: without // `nowrap`, a row too narrow for title + separator + suffix wraps the `+n` diff --git a/tsconfig.host.json b/tsconfig.host.json index e15bf83b24..01cca0cb14 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -42,6 +42,7 @@ "apps/web/tests/chat-scroll-fixture.ts", "apps/web/tests/trajectory-virtualization.e2e.ts", "apps/web/tests/lifecycle-chrome.e2e.ts", + "apps/web/tests/reasoning-preview.e2e.ts", "apps/web/tests/details-session-lifecycle.e2e.ts", "apps/web/tests/sessionless-header.e2e.ts", "apps/web/tests/document-preview.e2e.ts",